openapi: 3.1.0
info:
  title: AXIOM VERA Analysis Integration API
  version: 1.2.0
  description: Supplemental routes for the existing VERA API. All require operational mode and a verified OIDC identity, except that the /api/v1/analysis-apis routes marked "Demo" also answer when VERA_DEMO_MODE=1 without DATABASE_URL (actor demo-presenter, simulated calls only, demo store only); outside both modes they answer 503 PLATFORM_READ_ONLY before any store is read. This contract does not imply diagnostic qualification, a vendor agreement or a benchmark result.
servers:
  - url: /
    description: Use the deployment origin and configured application base path.
security:
  - bearerAuth: []
paths:
  /api/v1/normalization/validate:
    post:
      summary: Validate a typed evidence package without releasing it
      description: Roles lab_scientist, qa_officer, lab_director or platform_admin. Maximum body 16 MiB. Performs structural and cross-record checks, not analytical validation.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: './contracts/typed-evidence.schema.json'
      responses:
        '200':
          description: Structure checked; any release blockers are returned separately (releaseBlockers, typedReleaseFailures). A protein observation of an Olink lane that config/vera/release-lanes.v1.json keeps closed (every lane, by default) is a release blocker.
        '400':
          description: Invalid JSON
        '422':
          description: Schema or cross-record validation failed
        '413':
          description: Body exceeds the configured bound
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/engine-evaluations:
    get:
      summary: Read up to 100 recent engine comparison audit events
      description: Roles lab_scientist, qa_officer, lab_director or platform_admin.
      responses:
        '200':
          description: Recent immutable audit records
        default:
          $ref: '#/components/responses/Failure'
    post:
      summary: Record a paired holdout comparison for exact pipeline definitions
      description: Roles lab_scientist or platform_admin. Returns HOLD or ELIGIBLE_FOR_INDEPENDENT_REVIEW; never activates software. Maximum body 16 MiB.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: './contracts/engine-evaluation.schema.json'
      responses:
        '201':
          description: Evaluation ID, screened intervals and blockers recorded
        '409':
          description: Definitions are not an active baseline and inactive candidate in the same scope
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/pipelines/{pipelineId}/approve:
    post:
      summary: Independently approve or replace an analytical pipeline
      description: QA or laboratory director; creator cannot approve. Replacement additionally requires a passing evaluation made by a different identity and bound to both exact definition hashes.
      parameters:
        - $ref: '#/components/parameters/PipelineId'
        - in: header
          name: x-engine-evaluation-id
          required: false
          description: Required when another definition is active in the same instrument and assay scope
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Activated definition
        '409':
          description: Unapproved build, missing evaluation or separation-of-duties violation
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/pipelines/{pipelineId}/rollback:
    post:
      summary: Restore the exact recorded approved predecessor for new runs
      description: Laboratory director only and not the predecessor author. Current pipeline must still be active. Does not cancel jobs, change historical results or revoke releases.
      parameters:
        - $ref: '#/components/parameters/PipelineId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [previousPipelineId, reason, incidentReference]
              properties:
                previousPipelineId:
                  type: string
                  format: uuid
                reason:
                  type: string
                  minLength: 20
                  maxLength: 4000
                incidentReference:
                  type: string
                  minLength: 1
                  maxLength: 500
      responses:
        '200':
          description: Restoration audit event and active/retired pipeline IDs
        '409':
          description: Baseline mismatch, active pipeline changed, unapproved software or separation-of-duties violation
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/releases/{releaseId}/facts:
    get:
      summary: Retrieve current approved typed facts for a patient evidence graph
      description: Roles kg_service, qa_officer or lab_director, with signed vera_node_id and vera_jurisdiction matching the configured node. Checks current subject-recipient consent before reading object storage, verifies the immutable contextual bundle, and rechecks consent and release state before response. Current release lane is AXIOM. The receiver must independently enforce scope, retention and downstream revocation. No training or external-model export is authorized.
      parameters:
        - in: path
          name: releaseId
          required: true
          schema:
            type: string
        - in: query
          name: purpose
          required: false
          schema:
            type: string
            enum: [history, trend, current_state, personal_baseline, research]
            default: history
      responses:
        '200':
          description: Release identity, checksum, reviewer and typed evidence; referenceGraphWrite is false
        '409':
          description: Release unavailable, superseded, revoked or lacks eligible typed evidence
        '410':
          description: The subject's patient graph was erased on request (SUBJECT_ERASED); its evidence is no longer served
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/twin-access-decisions:
    post:
      summary: Append a reviewed subject and recipient access directive
      description: privacy_officer role and matching signed node claims required. Maximum body 64 KiB. Officer cannot alter their own recipient access. previousDecisionId must match the latest directive or be null for the first directive. An expired or revoked latest directive denies access; older grants are not revived. Evidence URI and hash are reviewed attestations, not automatically verified consent ceremonies.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: './contracts/twin-access-decision.schema.json'
      responses:
        '201':
          description: Decision ID, monotonically increasing revision, state and expiry. Retain decisionId for subsequent updates.
        '409':
          description: Latest directive identity changed; retry using the current reviewed decision
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/twin-evidence/assemble:
    post:
      summary: Assemble traceable longitudinal receipts from selected released evidence
      description: Roles kg_service, qa_officer or lab_director with signed node claims and current subject-recipient history consent. Maximum request 64 KiB, 20 releases, combined artifact size 64 MiB and 20000 facts. Rejects mixed subjects, node scopes and duplicate facts. Rechecks all directives and releases before response. Returns measurement series and per-purpose eligibility, not a diagnosis, personalized range, complete patient record or authorization to train models.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: './contracts/twin-evidence-request.schema.json'
      responses:
        '200':
          description: PREPAIRE-TWIN-EVIDENCE-RECEIPT@1.0.0 with source and method provenance, review and consent references, eligibility blockers and method-matched series. personalizedReferenceRange and homeostaticTarget remain null.
        '409':
          description: Evidence identity, purpose, consent revision or release-state conflict
        '410':
          description: A selected subject's patient graph was erased on request (SUBJECT_ERASED)
        '413':
          description: Request, artifact byte budget or fact limit exceeded
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subjects/{subjectToken}/cards:
    get:
      summary: Check signal cards for one subject, fused in memory with the reference graph
      description: Roles twin_app or kg_service, with signed vera_node_id and vera_jurisdiction matching the configured node. A current consent directive for this recipient must grant purpose current_state for every product in the subject's graph; it is checked before any segment is decrypted and again before the answer. Only segments of current releases (approved, not superseded, run still RELEASED) are read, and the releases are checked again before the answer. Only facts whose reviewed use policy still permits current-state use are carded; a trend is computed only when the directive also grants trend, over facts whose policy permits it. Each card carries the result comparator, and a goal from a source not signed off is shown with reviewed false and sets no status. Since 1.1.0 each card also carries personal_range (the person's own range for that result, ADR 0061 D7 basis 3) when the directive also grants personal_baseline; it is shown beside the goal and lab_interval and never changes status, crossed_limits or next_step. The answer adds index_cards (the latest value of each calculated index) and withheld (counts of personal ranges and indices computed but not presented because a source is not signed off; a pending personal range keeps its state with every value null). Since 1.2.0 personal_range.reason may also be no_model_scale (a reference-graph biological-variation estimate with no modelling scale stated for its analyte, so the range stays on the laboratory's reference interval). LOINC CURIEs alone go to the reference graph. Nothing is stored; Cache-Control no-store. 503 PATIENT_KG_NOT_CONFIGURED while the KEK is unset. Audited as twin.patient_graph.read with codes and counts only.
      parameters:
        - $ref: '#/components/parameters/SubjectToken'
      responses:
        '200':
          description: PREPAIRE-TWIN-CARDS@1.3.0 (cards with personal_range, index_cards, withheld, referenceRelease) plus segments, excluded.evidenceUse and access (decisionId, purpose, modelTraining false)
        '403':
          description: Role, node scope or consent missing (TWIN_ACCESS_DENIED for any product or purpose not granted, and for an empty graph without a grant)
        '409':
          description: Consent changed during retrieval (CONSENT_CHANGED), or a release read was revoked, superseded or ended by the LIMS during retrieval (RELEASE_REVOKED)
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subjects/{subjectToken}/timeline:
    get:
      summary: The subject's chronological medical-event timeline
      description: As cards, for purpose history. Encounters bracket their facts; facts that cannot be placed are listed in skipped with a reason, never dropped silently. Since 1.1.0 signed-off calculated indices are added as index_value events with a computed block (formulaHash, registryVersion, reviewed, reviewStatus, inputs, warnings) and withheld.indices counts pending ones left out.
      parameters:
        - $ref: '#/components/parameters/SubjectToken'
      responses:
        '200':
          description: PREPAIRE-TWIN-TIMELINE@1.1.0 (events, skipped, withheld) plus segments, excluded and access
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subjects/{subjectToken}/personal-ranges:
    get:
      summary: The subject's personal reference ranges ("what is normal for you")
      description: As cards, but the directive must grant both current_state and personal_baseline for every product in the subject's graph, checked before any segment is decrypted. Ranges are computed from the facts whose reviewed use permits personal_baseline (vera-personal-range-bayes@1.4.1, docs/INTELLIGENCE_LAYER.md); each is presented only when its latest result is also current-state evidence and every source it rests on (biological variation, the laboratory's reference interval, genotype prior) is signed off, otherwise it is listed in withheld by LOINC and reason (not_current, review_pending) with no value. A personal range never replaces, moves or widens a decision limit. Audited as twin.patient_graph.read with codes and counts only; Cache-Control no-store.
      parameters:
        - $ref: '#/components/parameters/SubjectToken'
      responses:
        '200':
          description: PREPAIRE-PERSONAL-RANGES@1.3.0 (ranges with basis, reason, low, high, setPoint, n, progress, excluded with reasons, bvSource with its kind (table or reference_graph), reviewed, unreviewed, latest, priorKind, ahead (where the next result is expected) and trajectory (the band at each earlier result, only when the directive also grants history); biologicalVariationConsidered, the first-party CVI estimates matched but too imprecise to use) plus withheld, trajectory (included, reason, withheldSteps), segments, excluded and access
        '403':
          description: Role, node scope or consent missing (TWIN_ACCESS_DENIED when current_state or personal_baseline is not granted)
        '409':
          description: Consent changed or a release read was revoked during retrieval
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subjects/{subjectToken}/event-tokens:
    get:
      summary: The timeline as an event-token sequence (PREPAIRE-TWIN-EVENT-VOCAB@1.0.0)
      description: As timeline, for purpose history. Demographic tokens, BOS, then each event's tokens with ETHOS time tokens between events; a lab is LAB_<loinc> and a decile token (Q_UNK without a qualified table). No model training or external export is authorised.
      parameters:
        - $ref: '#/components/parameters/SubjectToken'
      responses:
        '200':
          description: PREPAIRE-TWIN-EVENT-TOKENS@1.0.0 (tokens, events, unknownQuantiles) plus segments, excluded and access
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subject/cards:
    get:
      summary: Check signal cards for the person named in the VERA-Subject-Token header
      description: The same answer, roles, node scope, consent checks and audit as GET /api/twin/v1/subjects/{subjectToken}/cards, with the subject token in the VERA-Subject-Token request header and none in the address, so that no access log, proxy or history keeps it. The address to use for a new caller; the path form is kept as published. 400 SUBJECT_TOKEN_HEADER_REQUIRED when the header is absent or given twice (after the role check); 422 when its value is not a pseudonymous reference.
      parameters:
        - $ref: '#/components/parameters/SubjectTokenHeader'
      responses:
        '200':
          description: PREPAIRE-TWIN-CARDS@1.3.0, as the path form
        '400':
          description: The header is absent or given twice (SUBJECT_TOKEN_HEADER_REQUIRED)
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subject/timeline:
    get:
      summary: The medical-event timeline of the person named in the header
      description: The same answer, roles, node scope, consent checks and audit as GET /api/twin/v1/subjects/{subjectToken}/timeline, with the subject token in the VERA-Subject-Token request header and none in the address, so that no access log, proxy or history keeps it. The address to use for a new caller; the path form is kept as published. 400 SUBJECT_TOKEN_HEADER_REQUIRED when the header is absent or given twice (after the role check); 422 when its value is not a pseudonymous reference.
      parameters:
        - $ref: '#/components/parameters/SubjectTokenHeader'
      responses:
        '200':
          description: PREPAIRE-TWIN-TIMELINE@1.1.0, as the path form
        '400':
          description: The header is absent or given twice (SUBJECT_TOKEN_HEADER_REQUIRED)
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subject/personal-ranges:
    get:
      summary: The personal reference ranges of the person named in the header
      description: The same answer, roles, node scope, consent checks and audit as GET /api/twin/v1/subjects/{subjectToken}/personal-ranges, with the subject token in the VERA-Subject-Token request header and none in the address, so that no access log, proxy or history keeps it. The address to use for a new caller; the path form is kept as published. 400 SUBJECT_TOKEN_HEADER_REQUIRED when the header is absent or given twice (after the role check); 422 when its value is not a pseudonymous reference.
      parameters:
        - $ref: '#/components/parameters/SubjectTokenHeader'
      responses:
        '200':
          description: PREPAIRE-PERSONAL-RANGES@1.3.0, as the path form
        '400':
          description: The header is absent or given twice (SUBJECT_TOKEN_HEADER_REQUIRED)
        default:
          $ref: '#/components/responses/Failure'
  /api/twin/v1/subject/event-tokens:
    get:
      summary: The event-token sequence of the person named in the header
      description: The same answer, roles, node scope, consent checks and audit as GET /api/twin/v1/subjects/{subjectToken}/event-tokens, with the subject token in the VERA-Subject-Token request header and none in the address, so that no access log, proxy or history keeps it. The address to use for a new caller; the path form is kept as published. 400 SUBJECT_TOKEN_HEADER_REQUIRED when the header is absent or given twice (after the role check); 422 when its value is not a pseudonymous reference.
      parameters:
        - $ref: '#/components/parameters/SubjectTokenHeader'
      responses:
        '200':
          description: PREPAIRE-TWIN-EVENT-TOKENS@1.0.0, as the path form
        '400':
          description: The header is absent or given twice (SUBJECT_TOKEN_HEADER_REQUIRED)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/patient-kg/outbox:
    get:
      summary: The patient-graph outbox, with counts and writer status
      description: Roles platform_admin, security_auditor or lab_director (OUTBOX_READERS). Newest 200 rows (eventId, kind, release ids, state, attempts, lastError code), counts by kind and state, segment counts by state, and the writer and reference-graph status. Never a subject token or value. ?state= and ?kind= filter.
      responses:
        '200':
          description: PREPAIRE-PATIENT-KG-OUTBOX@1.0.0
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/patient-kg/outbox/process:
    post:
      summary: Run one patient-graph outbox pass now
      description: Role platform_admin (OUTBOX_OPERATORS). The pass the worker runs on its own loop. 503 PATIENT_KG_WRITER_DISABLED while the KEK is unset or the reference graph is misconfigured. Audited as patient_kg.outbox.process_run.
      responses:
        '200':
          description: PREPAIRE-PATIENT-KG-PROCESS-RUN@1.0.0 (recovered, attempted, done, retrying, failed)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/patient-kg/subject/summary:
    get:
      summary: One subject's graph from the clear columns only
      description: The person is named in the VERA-Subject-Token request header, never in the address (the path form /api/v1/patient-kg/subjects/{subjectToken}/summary is withdrawn). Roles platform_admin, security_auditor or lab_director. Key state, and per segment its id, release, run, product, state and node, edge and held counts with the operational held reasons (unknown_identity, unpinned_reference_release, unadmitted_software_digest, schema_violation). Clinical held reasons stay inside the ciphertext and count only in heldCount. Nothing is decrypted; never a value, fact id or gene. Audited as patient_kg.subject.summary_read.
      parameters:
        - $ref: '#/components/parameters/SubjectTokenHeader'
      responses:
        '200':
          description: PREPAIRE-PATIENT-KG-SUBJECT-SUMMARY@1.0.0
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/patient-kg/subject/erase:
    post:
      summary: Crypto-shred one subject's graph (irreversible)
      description: The person is named in the VERA-Subject-Token request header, never in the address (the path form /api/v1/patient-kg/subjects/{subjectToken}/erase is withdrawn). Role privacy_officer with signed node claims; the body must be application/json and a browser request must be same-origin (Sec-Fetch-Site). Destroys the wrapped data key (or leaves a destroyed tombstone) and marks every segment ERASED with its sealed bytes emptied; no segment can be decrypted again, no new one is written, and the subject's released evidence is no longer served to apps (410 SUBJECT_ERASED). Copies of the database taken before the erasure (backups, archives, replicas) still hold the wrapped key until they age out. Works without the KEK. Audited as patient_kg.subject.erased with the request reference.
      parameters:
        - $ref: '#/components/parameters/SubjectTokenHeader'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [requestReference, confirmSubjectToken]
              properties:
                requestReference:
                  type: string
                  pattern: '^[A-Za-z0-9][A-Za-z0-9._:/-]{2,99}$'
                  description: The governed erasure request's reference (a ticket id), never free text; it stays in the append-only audit chain
                confirmSubjectToken:
                  type: string
                  description: Must repeat the subject token of the VERA-Subject-Token header (422 ERASURE_CONFIRMATION_MISMATCH otherwise)
      responses:
        '200':
          description: PREPAIRE-PATIENT-KG-ERASURE@1.0.0 (keyDestroyed, segmentsErased)
        '403':
          description: Role, node scope, or a cross-site browser request (CROSS_SITE_REQUEST_REFUSED)
        '415':
          description: The body is not application/json (JSON_CONTENT_TYPE_REQUIRED)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/first-party:
    get:
      summary: First-party knowledge export status
      description: Roles platform_admin, security_auditor, lab_director or privacy_officer (FIRST_PARTY_READERS). The package contract, the KG schema its cells map to (PREPAIRE-KG-SCHEMA@1.2.0), the method ids and versions with their primary sources (DOI or URL), the consent recipient, the node's configured export settings (config/vera/first-party.v1.json, PREPAIRE-FIRST-PARTY-EXPORT-CONFIG@1.0.0; the analytical CVs left out), and the node's signing status (configured, key id, SPKI public key and its SHA-256; never the private key). See src/lib/first-party/README.md.
      responses:
        '200':
          description: PREPAIRE-FIRST-PARTY-STATUS@1.0.0
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/first-party/packages:
    post:
      summary: Export one signed first-party knowledge package for a closed period
      description: Role lab_director with signed node claims; the body must be application/json and a browser request must be same-origin (Sec-Fetch-Site). Cohort statistics (reference intervals by kosmic, biological variation by CV-ANOVA, within-person co-movement by repeated measures correlation) of every released, measured result whose subject's consent directive grants research to the reference graph and whose own reviewed use permits research; consent is checked from the clear columns before anything is decrypted; small cells are suppressed and counted, values rounded, counts rounded down. The settings (age bands, rounding, floors, estimator settings) are the node's reviewed configuration, config/vera/first-party.v1.json, never the request. The node's export ledger refuses, before anything is decrypted, a period that overlaps an exported one unless every overlapping partition is identical (409 EXPORT_OVERLAPS_RELEASED_PARTITION), and a differentially private export over the node's cumulative epsilon cap (409 DP_BUDGET_EXHAUSTED). Answers the package file itself (RFC 8785 canonical JSON plus a newline, SHA-256 digest, Ed25519 signature with the node key; Content-Disposition attachment), the bytes the reference graph admits. Needs the patient-graph KEK (503 PATIENT_KG_NOT_CONFIGURED) and the node's signing key (503 FIRST_PARTY_SIGNING_KEY_NOT_CONFIGURED). The released partitions and the audit event first_party.package.exported (ids, the digest and counts only) are recorded in one transaction.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [period, requestReference]
              properties:
                period:
                  type: object
                  additionalProperties: false
                  required: [from, to]
                  description: Whole calendar months, at most 60, ended before the day of the export (422 PERIOD_INVALID otherwise)
                  properties:
                    from: { type: string, format: date }
                    to: { type: string, format: date }
                requestReference:
                  type: string
                  pattern: '^[A-Za-z0-9][A-Za-z0-9._:/-]{2,99}$'
                  description: The governed request's reference (a ticket id), never free text
      responses:
        '200':
          description: PREPAIRE-FIRST-PARTY-KNOWLEDGE@1.1.0 (contracts/prepaire-first-party-v1), as application/json; charset=utf-8, Cache-Control no-store
        '403':
          description: Role, node scope, or a cross-site browser request (CROSS_SITE_REQUEST_REFUSED)
        '409':
          description: The period overlaps an exported one with a differing partition (EXPORT_OVERLAPS_RELEASED_PARTITION), or the node's differential-privacy budget is spent (DP_BUDGET_EXHAUSTED)
        '415':
          description: The body is not application/json (JSON_CONTENT_TYPE_REQUIRED)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/models:
    get:
      summary: The model registry with each model's admission state
      description: Roles platform_admin, security_auditor or lab_director (OUTBOX_READERS). Registry fields of config/vera/models.v1.json, each model's failing admission rules (LICENCE_NOT_COMMERCIAL, LICENCE_EVIDENCE_MISSING, DIGEST_NOT_PINNED, SOFTWARE_BUILD_NOT_APPROVED, REVIEW_SIGN_OFF_MISSING, INFERENCE_PROVENANCE_MISSING, SOURCES_MISSING, VIEW_NOT_SUPPORTED_BY_CONTRACT, ENGINE_UNKNOWN, ENGINE_NOT_PINNED, LEGAL_BASIS_MISSING), the engines with whether their endpoint variable is set (never its value), and gateway (checkedIn this_process), which says whether the gateway could run in the platform process that answered, with the reason when not. The worker decides from its own environment and logs its own status; in the DGX overlay only the worker has the engine URL, so this reports off there.
      responses:
        '200':
          description: PREPAIRE-MODEL-GATEWAY-REGISTRY@1.0.0 (registry, engines, gateway, admitted, models)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/models/jobs:
    get:
      summary: The model gateway's job outbox, with counts
      description: Roles platform_admin, security_auditor or lab_director. Newest 200 jobs (jobId, modelId, modelVersion, state, attempts, triggerReleaseId, derivedRunId and derivedRunPath, skipReasons, lastError code, times), counts by state and by model. A job holds no subject token, input or output value. ?state= and ?modelId= filter (422 on an unknown state or a malformed modelId; a well-formed modelId outside the registry, such as a removed model's, returns its rows).
      responses:
        '200':
          description: PREPAIRE-MODEL-GATEWAY-JOBS@1.0.0 (counts, countsByModel, rows)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/models/jobs/process:
    post:
      summary: Ask the worker to process pending model-gateway jobs now
      description: Role platform_admin (OUTBOX_OPERATORS); a browser request must be same-origin (Sec-Fetch-Site). Every PENDING job becomes due, so the worker's next loop pass picks it up instead of waiting out its backoff. The pass runs only in the worker, the one process on the internal models network with the engine URL; the platform never decrypts a graph for a model or calls an engine. BLOCKED and FAILED jobs need the requeue route. Audited as model_gateway.jobs.process_requested under the operator's role, with the count only.
      responses:
        '202':
          description: PREPAIRE-MODEL-GATEWAY-PROCESS-REQUEST@1.0.0 (pendingMadeDue, runner worker)
        '403':
          description: Role, or a cross-site browser request (CROSS_SITE_REQUEST_REFUSED)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/models/jobs/{jobId}/requeue:
    post:
      summary: Requeue a BLOCKED or FAILED model job
      description: Role platform_admin; a browser request must be same-origin. The job becomes PENDING with a fresh retry budget; a job that filed a derived run is never requeued. Audited as model_gateway.job.requeued.
      parameters:
        - in: path
          name: jobId
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: PREPAIRE-MODEL-GATEWAY-REQUEUE@1.0.0 (jobId, state PENDING)
        '409':
          description: The job is not BLOCKED or FAILED, or already filed a derived run (MODEL_JOB_NOT_REQUEUEABLE)
        '422':
          description: The job id is not a UUID (JOB_ID_INVALID)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis:
    get:
      summary: Analysis engine catalogue
      description: Roles platform_admin, lab_scientist, lab_director, qa_officer, security_auditor, privacy_officer, legal_approver or instrument_operator (ANALYSIS_VIEWERS). Demo open. Engines from config/vera/analysis-engines.v1.json with the agreement record resolved from config/vera/platform-status.v1.json, the installation without secrets (credentialConfigured; the 8-hex credential fingerprint, an HMAC under a server key, for platform_admin only, null for every other role), the connection mode (real, or simulated with its reason), effective selections and last call; the genomic pipeline selection; where the API call log lives; the policy text.
      responses:
        '200':
          description: PREPAIRE-ANALYSIS-API@1.0.0 (AnalysisApisCatalogResponse in src/lib/analysis-apis/types.ts)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/selection:
    get:
      summary: Genomic pipeline selection with effective states
      description: As GET /api/v1/analysis-apis. Every pipeline, stage and assignment with its effective state (candidate, selected-for-benchmark, approved or retired), approval requirements and blockers. Approved is computed from attestations, never declared; without a database the state is at most selected-for-benchmark.
      responses:
        '200':
          description: PREPAIRE-ANALYSIS-SELECTION@1.0.0
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/selection/change-requests:
    get:
      summary: Recorded selection change requests
      description: As GET /api/v1/analysis-apis. Partner mode masks the requester.
      responses:
        '200':
          description: '{recordedIn, items}'
        default:
          $ref: '#/components/responses/Failure'
    post:
      summary: Record a request to change one assignment's declared selection
      description: Roles lab_scientist, lab_director or qa_officer. Demo writes to the demo store. Body {stackKey, stageKey, engineId, role, declared, change (select-for-benchmark, back-to-candidate, retire or make-primary), reason}. Records the request only (an AuditEvent in operational mode); the selection changes only in config/vera/genomic-pipelines.v1.json.
      responses:
        '201':
          description: '{request: {requestId, recordedIn, simulated}}'
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/engines/{engineId}:
    parameters:
      - $ref: '#/components/parameters/EngineId'
    get:
      summary: One analysis engine
      description: As GET /api/v1/analysis-apis (the credential fingerprint for platform_admin only).
      responses:
        '200':
          description: EngineView
        '404':
          description: ENGINE_UNKNOWN
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/engines/{engineId}/install:
    parameters:
      - $ref: '#/components/parameters/EngineId'
    post:
      summary: Install an analysis engine API on this site
      description: Operational only, platform_admin, needs DATABASE_URL. Upserts AnalysisApiInstallation state installed. AuditEvent analysis_api.installed.
      responses:
        '201':
          description: PREPAIRE-ANALYSIS-API-INSTALLATION@1.0.0 without secrets
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/engines/{engineId}/connection:
    parameters:
      - $ref: '#/components/parameters/EngineId'
    post:
      summary: Set the endpoint, authentication and residency of an installed engine
      description: Operational only, platform_admin, needs DATABASE_URL. Body baseUrl (http or https, no userinfo, query or fragment; https whenever the auth scheme sends a credential, and for cloud and mTLS; for on_prem and sovereign a private address or a name under the site's DNS suffixes in config/vera/site.v1.json networks; loopback, link-local, metadata, multicast and reserved addresses, localhost, metadata host names and single-label names refused for every class), authScheme (one of the engine's), credential, clientId, tokenUrl (https, no userinfo, query or fragment, the same host rule), residencyClass (one of the engine's allowedResidencyClasses), region, projectRef, caCertificate, clientCertificateChain with clientPrivateKey (cleared when the scheme is not mtls), apiPaths {health, submit, status, results}. An engine that may also be cloud is set to on_prem or sovereign only after a RESIDENCY_CLASSIFICATION for that host (409 RESIDENCY_CLASSIFICATION_REQUIRED). Secrets are write-only; a blank secret keeps the stored one. AuditEvent analysis_api.connection_set carries flags only, never a secret or a digest of one.
      responses:
        '200':
          description: PREPAIRE-ANALYSIS-API-INSTALLATION@1.0.0 without secrets
        '409':
          description: API_NOT_INSTALLED or RESIDENCY_CLASSIFICATION_REQUIRED
        '422':
          description: Invalid connection input or a rule of the engine or the site network (CONNECTION_RULES - residency, host, auth scheme, https)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/engines/{engineId}/disable:
    parameters:
      - $ref: '#/components/parameters/EngineId'
    post:
      summary: Disable an installed engine and clear its credential
      description: Operational only, platform_admin, needs DATABASE_URL. AuditEvent analysis_api.disabled. Later dispatches to the engine are blocked with INSTALLATION_DISABLED.
      responses:
        '200':
          description: Installation without secrets
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/engines/{engineId}/test:
    parameters:
      - $ref: '#/components/parameters/EngineId'
    post:
      summary: Connection test
      description: Roles platform_admin or lab_scientist; demo simulated only. WES or TES service-info, or the vendor health path. Always writes one testConnection row to the API call log (plus authenticate rows for OAuth2) and updates the installation's last check when a database is present.
      responses:
        '200':
          description: PREPAIRE-ANALYSIS-API-CONNECTION-TEST@1.0.0 with callId, simulated flag and reason
        '502':
          description: The engine did not answer as expected (same body)
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/engines/{engineId}/attestations:
    parameters:
      - $ref: '#/components/parameters/EngineId'
    get:
      summary: Attestations behind an engine's selections
      description: As GET /api/v1/analysis-apis. Empty with attestationsAvailable false without a database.
      responses:
        '200':
          description: EngineAttestation list
        default:
          $ref: '#/components/responses/Failure'
    post:
      summary: Record an append-only attestation
      description: Operational only, needs DATABASE_URL. BENCHMARK_EVIDENCE lab_scientist, QA_REVIEW qa_officer, LAB_DIRECTOR_APPROVAL lab_director, LEGAL_ASSESSMENT legal_approver, RETIREMENT lab_director or qa_officer, RESIDENCY_CLASSIFICATION privacy_officer or legal_approver; platform_admin never attests. The identity must equal the configured version and digest (a placeholder digest is 409 IDENTITY_PLACEHOLDER); one person cannot attest two approval kinds for the same identity (409 SAME_IDENTITY); passed BENCHMARK_EVIDENCE needs an engineEvaluationId (422 EVALUATION_REQUIRED), whose report is re-evaluated with evaluateEngine (409 EVALUATION_NOT_ELIGIBLE), recorded by a different person (409 EVALUATION_SAME_IDENTITY), whose unchanged candidate pipeline runs this digest for an instrument profile of the stack (409 EVALUATION_SCOPE_MISMATCH) and whose evaluationSha256 is the evidenceSha256 (409 EVALUATION_EVIDENCE_MISMATCH); RESIDENCY_CLASSIFICATION names residencyClass on_prem or sovereign and the endpointHost (host or host:port) of an engine that may also be cloud, a host on the site network; LEGAL_ASSESSMENT needs a future validUntil, a residencyClass and dataClasses limited to pseudonymized-vcf and human-depleted (native or genome is 422 DATA_CLASS_NEVER_LEAVES). AuditEvent analysis_engine.attested.
      responses:
        '201':
          description: Attestation with the recomputed effective selection
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/dispatch/plan:
    post:
      summary: Preview a dispatch
      description: Roles lab_scientist, platform_admin, lab_director or qa_officer; demo open. Body {source {kind ingestion-run, edge-capture, sample-run or reference-material, id}, stackKey, purpose benchmark or production, includeComparators}. Writes nothing and calls nothing. Per stage and assignment the mode (real, simulated, blocked or skipped), the simulation reason, the blockers, the inputs with SHA-256 and data class, and the residency decision, including the would-be decision for skipped candidates.
      responses:
        '200':
          description: PREPAIRE-ANALYSIS-DISPATCH-PLAN@1.0.0
        '404':
          description: SOURCE_NOT_FOUND
        '409':
          description: SOURCE_NOT_SEALED
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/dispatch:
    post:
      summary: Dispatch a sealed source to the selected engines per stage
      description: Roles lab_scientist or platform_admin with an Idempotency-Key header; demo simulated only (503 DEMO_STORE_ONLY when DATABASE_URL is set; an Idempotency-Key is honoured). Same body as the plan. Writes one AnalysisApiCall row per attempted call and one blocked row per policy refusal (nothing sent); AuditEvent analysis_api.dispatched with the call ids on the database. A replayed key answers the first result with the header idempotent-replayed true. With operational access an edge-capture or sample-run source (demo VERA Edge store) is 422 DEMO_SOURCE_IN_OPERATIONAL. Demo writes are limited to 60 a minute per client (429 DEMO_RATE_LIMITED) and the demo store is capped (507 DEMO_STORE_FULL).
      parameters:
        - in: header
          name: Idempotency-Key
          required: false
          schema:
            type: string
      responses:
        '201':
          description: PREPAIRE-ANALYSIS-DISPATCH@1.0.0 (dispatchId, plan, outcomes with call ids, log store)
        '404':
          description: SOURCE_NOT_FOUND
        '409':
          description: SOURCE_NOT_SEALED
        '422':
          description: DEMO_SOURCE_IN_OPERATIONAL
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/calls:
    get:
      summary: THE API call log
      description: As GET /api/v1/analysis-apis. Filters engine, operation, outcome, simulated, residency (permitted or refused), run, dispatch, job, from, to; newest first; cursor and limit up to 200. One subject's calls are asked for with the VERA-Subject-Token request header; a subject token in the address (?subject=) is refused (422 SUBJECT_TOKEN_IN_ADDRESS). Partner mode masks subject tokens, real hosts and actor ids, and refuses the subject filter (403 SUBJECT_FILTER_UNAVAILABLE). In operational mode an unreadable database is 503 CALL_LOG_UNAVAILABLE (never the demo store); the same holds for /calls/{callId}, /calls/verify and /calls/export.
      responses:
        '200':
          description: PREPAIRE-ANALYSIS-API-CALLS@1.0.0 with the store that answered
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/calls/{callId}:
    parameters:
      - $ref: '#/components/parameters/CallId'
    get:
      summary: One logged call with its follow-ups
      description: As GET /api/v1/analysis-apis. Host and path, request SHA-256, inputs with SHA-256 and data class, residency decision, engine identity, external job id, HTTP status and duration (null for a simulated call, which no engine answered), result references, actor, simulated flag and reason, previousHash and entryHash. Bodies and secrets are never stored.
      responses:
        '200':
          description: ApiCallLogDetail
        '404':
          description: CALL_NOT_FOUND
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/calls/{callId}/refresh:
    parameters:
      - $ref: '#/components/parameters/CallId'
    post:
      summary: Follow up a submit call
      description: As POST /dispatch. A status call, plus a results call once complete; each is a new row with parentCallId.
      responses:
        '200':
          description: '{parentCallId, state, calls, detail}'
        '409':
          description: NOT_A_SUBMIT_CALL or JOB_ID_MISSING
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/calls/verify:
    get:
      summary: Verify the hash chain of the API call log
      description: Roles security_auditor, platform_admin or qa_officer; demo open. Recomputes every entryHash and previousHash link of the store that answers.
      responses:
        '200':
          description: PREPAIRE-ANALYSIS-API-CALL-CHAIN@1.0.0 with valid, count, headHash and firstBrokenSeq
        default:
          $ref: '#/components/responses/Failure'
  /api/v1/analysis-apis/calls/export:
    get:
      summary: Export the API call log for auditors
      description: Roles security_auditor or platform_admin; demo open. Same filters as GET /calls.
      responses:
        '200':
          description: One log entry per line (newline-delimited JSON), sent as application/octet-stream, which no proxy rewrites, named analysis-api-calls.ndjson, with its SHA-256 in x-content-sha256
        default:
          $ref: '#/components/responses/Failure'
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
  parameters:
    SubjectToken:
      in: path
      name: subjectToken
      required: true
      schema:
        type: string
        pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$'
        description: The pseudonymous twin subject token; never a name or contact detail
    SubjectTokenHeader:
      in: header
      name: VERA-Subject-Token
      required: true
      schema:
        type: string
        pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$'
        description: The pseudonymous twin subject token, sent once in this request header so that no address carries it; never a name or contact detail
    EngineId:
      in: path
      name: engineId
      required: true
      schema:
        type: string
        description: An engine id from config/vera/analysis-engines.v1.json
    CallId:
      in: path
      name: callId
      required: true
      schema:
        type: string
        pattern: '^aac_[0-9a-f]{32}$'
    PipelineId:
      in: path
      name: pipelineId
      required: true
      schema:
        type: string
        format: uuid
  responses:
    Failure:
      description: 400 invalid JSON, 401 invalid identity, 403 insufficient role, 404 missing resource, 409 failed gate, 413 body limit, 422 failed validation, 429 demo rate limit, 503 unavailable/read-only or 507 demo store full. Body includes error code, message and requestId. On the analysis API routes the requestId is the x-request-id header when it matches ^[A-Za-z0-9._:-]{1,128}$, otherwise a fresh UUID.
