{
  "openapi": "3.1.0",
  "jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema",
  "info": {
    "title": "Poieti HIS integration",
    "version": "1.0.0",
    "summary": "The hospital push API and the Poieti HIS Web Service, sharing DeliveryV1.",
    "description": "Poieti delivers confirmed records to the hospital. **Hospital push API**: the hospital implements these routes under its configured base URL and Poieti calls them, signed with X-Poieti-Signature.\n\n**Poieti HIS Web Service** (`/his/v1`): the hospital calls these routes with a `phis` machine key to download attachment bytes, read delivery status, list deliveries for reconciliation and upload ward census.\n\nOn the Poieti hosts only `/his/v1/*` and an unauthenticated `GET /health` respond. Allowlist the hostname (Cloudflare anycast, no fixed IP) on outbound port 443 and exempt it from TLS inspection.\n\nPoieti's machine responses carry `Cache-Control: no-store`; errors are `{error, code, requestId}` and behavior depends on `code`.\n\nRequest bodies sent to Poieti are closed (unknown members are refused); readers of Poieti's bodies should ignore members they do not know.\n\nEvery error code a request to these routes can receive is listed, with its HTTP status, in `x-poieti-error-codes`; a path outside them answers 404 `HIS_NOT_FOUND`."
  },
  "servers": [
    {
      "url": "https://his.poieti.com",
      "description": "Production"
    },
    {
      "url": "https://his-dev.poieti.com",
      "description": "Development (acceptance testing)"
    }
  ],
  "tags": [
    {
      "name": "Poieti HIS Web Service",
      "description": "Called by the hospital with a `phis` key."
    },
    {
      "name": "Hospital push API",
      "description": "Implemented by the hospital; called by Poieti."
    }
  ],
  "x-poieti-error-codes": {
    "HIS_UNAUTHORIZED": {
      "status": 401,
      "description": "Missing, malformed, unknown, revoked or expired key; no detail is given."
    },
    "HIS_IP_NOT_ALLOWED": {
      "status": 403,
      "description": "The request address is outside the credential's allowed CIDRs."
    },
    "HIS_SCOPE_DENIED": {
      "status": 403,
      "description": "The credential lacks the route's scope, or the census ward is not among its census wards."
    },
    "HIS_CENSUS_DISABLED": {
      "status": 409,
      "description": "Census upload while the institution does not accept census."
    },
    "HIS_RATE_LIMITED": {
      "status": 429,
      "description": "More than 120 requests per minute for this credential; honor Retry-After."
    },
    "HIS_REQUEST_INVALID": {
      "status": 422,
      "description": "Invalid query parameters."
    },
    "HIS_BODY_TOO_LARGE": {
      "status": 413,
      "description": "Request body over the census upload's limit (2 MB)."
    },
    "DELIVERY_NOT_FOUND": {
      "status": 404,
      "description": "No delivery with this id in the institution (a malformed id is treated as unknown)."
    },
    "HIS_ATTACHMENT_NOT_FOUND": {
      "status": 404,
      "description": "The delivery is not leased or written, its payload was purged, or it does not contain this attachment."
    },
    "WARD_NOT_FOUND": {
      "status": 404,
      "description": "No ward with this HIS code."
    },
    "CENSUS_STALE": {
      "status": 409,
      "description": "asOf is older than the ward's last applied snapshot, or equal with different content."
    },
    "HIS_CENSUS_INVALID": {
      "status": 422,
      "description": "Invalid snapshot: schema, missing offset, asOf too far ahead or too old, repeated chart number or encounter."
    },
    "CENSUS_CONTEXT_DISABLED": {
      "status": 422,
      "description": "allergies, alerts or vitals sent while the institution is not in push mode."
    },
    "HIS_INTERNAL_ERROR": {
      "status": 500,
      "description": "Unexpected failure; retry later."
    }
  },
  "paths": {
    "/his/v1/integration": {
      "get": {
        "operationId": "getIntegration",
        "tags": [
          "Poieti HIS Web Service"
        ],
        "summary": "Integration settings and server time",
        "description": "Any scope. Use `serverTime` to check clock skew.",
        "security": [
          {
            "poietiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Current settings.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrationResponse"
                },
                "examples": {
                  "push": {
                    "summary": "Push-mode institution",
                    "externalValue": "examples/integration.json"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/his/v1/deliveries": {
      "get": {
        "operationId": "listDeliveries",
        "tags": [
          "Poieti HIS Web Service"
        ],
        "summary": "Delivery metadata for reconciliation",
        "description": "Scope `deliveries`. Keyset paging by `(updatedAt, deliveryId)`: a full page carries `nextAfter` (the next page may be empty), a short page ends the listing. No identity or clinical values.",
        "security": [
          {
            "poietiKey": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/State"
          },
          {
            "$ref": "#/components/parameters/UpdatedSince"
          },
          {
            "$ref": "#/components/parameters/After"
          },
          {
            "$ref": "#/components/parameters/Limit"
          }
        ],
        "responses": {
          "200": {
            "description": "One page.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeliveryListResponse"
                },
                "examples": {
                  "page": {
                    "summary": "First page",
                    "externalValue": "examples/delivery-list.json"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "422": {
            "$ref": "#/components/responses/RequestInvalid"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/his/v1/deliveries/{deliveryId}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/DeliveryId"
        }
      ],
      "get": {
        "operationId": "getDeliveryStatus",
        "tags": [
          "Poieti HIS Web Service"
        ],
        "summary": "One delivery's state",
        "description": "Scope `deliveries`. No identity or clinical values.",
        "security": [
          {
            "poietiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Delivery metadata.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeliveryStatus"
                },
                "examples": {
                  "written": {
                    "summary": "Written create",
                    "externalValue": "examples/delivery-status.json"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/DeliveryNotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/his/v1/deliveries/{deliveryId}/attachments/{attachmentId}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/DeliveryId"
        },
        {
          "$ref": "#/components/parameters/AttachmentId"
        }
      ],
      "get": {
        "operationId": "getDeliveryAttachment",
        "tags": [
          "Poieti HIS Web Service"
        ],
        "summary": "Attachment bytes of a delivery",
        "description": "Scope `deliveries`. Push requests carry attachment metadata only; the endpoint fetches the bytes here. An unknown delivery → 404 `DELIVERY_NOT_FOUND`. Only for `leased` or `written` deliveries whose payload is not purged and lists this attachment. Verify `Content-Length` and the SHA-256 against the delivery before writing.",
        "security": [
          {
            "poietiKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "The stored bytes with their stored media type.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              },
              "Content-Length": {
                "$ref": "#/components/headers/ContentLength"
              },
              "Digest": {
                "$ref": "#/components/headers/Digest"
              }
            },
            "content": {
              "*/*": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "application/octet-stream"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Unknown delivery or attachment.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "DELIVERY_NOT_FOUND": {
                    "summary": "DELIVERY_NOT_FOUND",
                    "value": {
                      "error": "Delivery not found.",
                      "code": "DELIVERY_NOT_FOUND",
                      "requestId": "8c1f0a5e2b7d4c39a6e1"
                    }
                  },
                  "HIS_ATTACHMENT_NOT_FOUND": {
                    "summary": "HIS_ATTACHMENT_NOT_FOUND",
                    "externalValue": "examples/error.json"
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/his/v1/census/wards/{wardCode}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/WardCode"
        }
      ],
      "put": {
        "operationId": "uploadCensus",
        "tags": [
          "Poieti HIS Web Service"
        ],
        "summary": "Upload one ward's census snapshot",
        "description": "Scope `census`, and the ward must be among the credential's census wards (empty means every ward). A credential limited to some wards changes only patients that are new or already in one of its wards: a listed patient of another ward (or one whose encounter another ward's patient holds) is rejected as `OUT_OF_SCOPE` and left unchanged, so a transfer between wards needs a credential covering both, or one without a ward limit. Accepted while the institution accepts census, also before deliveries are switched on; clinical context only in push mode. Census never releases held deliveries and never changes a record's stay pin.",
        "security": [
          {
            "poietiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CensusSnapshotV1"
              },
              "examples": {
                "identity": {
                  "summary": "Identity and admission data",
                  "externalValue": "examples/census-snapshot.json"
                },
                "context": {
                  "summary": "With clinical context (push mode)",
                  "externalValue": "examples/census-snapshot-context.json"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Applied (or replayed).",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CensusResult"
                },
                "examples": {
                  "applied": {
                    "summary": "Applied snapshot",
                    "externalValue": "examples/census-result.json"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "description": "Unknown ward code.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "WARD_NOT_FOUND": {
                    "summary": "WARD_NOT_FOUND",
                    "value": {
                      "error": "No ward has this HIS code.",
                      "code": "WARD_NOT_FOUND",
                      "requestId": "8c1f0a5e2b7d4c39a6e1"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The snapshot is stale or census is disabled.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "CENSUS_STALE": {
                    "summary": "CENSUS_STALE",
                    "value": {
                      "error": "A newer snapshot was already applied to this ward.",
                      "code": "CENSUS_STALE",
                      "requestId": "8c1f0a5e2b7d4c39a6e1"
                    }
                  },
                  "HIS_CENSUS_DISABLED": {
                    "summary": "HIS_CENSUS_DISABLED",
                    "value": {
                      "error": "This institution does not accept census.",
                      "code": "HIS_CENSUS_DISABLED",
                      "requestId": "8c1f0a5e2b7d4c39a6e1"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/BodyTooLarge"
          },
          "422": {
            "description": "Invalid snapshot.",
            "headers": {
              "Cache-Control": {
                "$ref": "#/components/headers/NoStore"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "HIS_CENSUS_INVALID": {
                    "summary": "HIS_CENSUS_INVALID",
                    "value": {
                      "error": "asOf must include a time zone offset.",
                      "code": "HIS_CENSUS_INVALID",
                      "requestId": "8c1f0a5e2b7d4c39a6e1"
                    }
                  },
                  "CENSUS_CONTEXT_DISABLED": {
                    "summary": "CENSUS_CONTEXT_DISABLED",
                    "value": {
                      "error": "Clinical context is accepted only in push mode.",
                      "code": "CENSUS_CONTEXT_DISABLED",
                      "requestId": "8c1f0a5e2b7d4c39a6e1"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/deliveries": {
      "servers": [
        {
          "url": "{baseUrl}",
          "description": "The hospital endpoint configured with `set-his-endpoint` (public HTTPS, no query or fragment).",
          "variables": {
            "baseUrl": {
              "default": "https://his.example.org/poieti/v1"
            }
          }
        }
      ],
      "post": {
        "operationId": "pushDelivery",
        "tags": [
          "Hospital push API"
        ],
        "summary": "Write one delivery into the HIS (implemented by the hospital)",
        "description": "Poieti sends the canonical DeliveryV1 (RFC 8785 JSON: sorted keys, no whitespace) with identical bytes on every attempt of a deliveryId. Deduplicate writes on deliveryId (= Idempotency-Key = X-Poieti-Delivery): a repeated deliveryId that is already written returns 200 with the original hisRecordId (or 409 `DUPLICATE_DELIVERY` with hisRecordId). Store only successful writes against the key: a rejected deliveryId is processed again on a console retry. Return 202 when the write is queued; Poieti then polls `GET /deliveries/{deliveryId}`. Use 401/403 only for endpoint credential failures; refuse a single record with a coded 4xx (for example 422).",
        "security": [
          {
            "poietiSignature": []
          },
          {
            "poietiSignature": [],
            "hospitalBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "$ref": "#/components/parameters/PoietiDelivery"
          },
          {
            "$ref": "#/components/parameters/PoietiAttempt"
          },
          {
            "$ref": "#/components/parameters/UserAgent"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DeliveryV1"
              },
              "examples": {
                "create": {
                  "summary": "Create",
                  "externalValue": "examples/delivery-create.json"
                },
                "correction": {
                  "summary": "Correction",
                  "externalValue": "examples/delivery-correction.json"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Written (or a repeat of a written deliveryId).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushWriteResponse"
                },
                "examples": {
                  "written": {
                    "summary": "Written",
                    "externalValue": "examples/push-written.json"
                  }
                }
              }
            }
          },
          "201": {
            "description": "Written.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushWriteResponse"
                }
              }
            }
          },
          "202": {
            "description": "Queued; Poieti polls `GET /deliveries/{deliveryId}`. The body is ignored."
          },
          "409": {
            "description": "`DUPLICATE_DELIVERY` with hisRecordId means written; any other 409 is endpoint-suspect.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushError"
                },
                "examples": {
                  "duplicate": {
                    "summary": "Already written",
                    "externalValue": "examples/push-duplicate.json"
                  }
                }
              }
            }
          },
          "422": {
            "description": "Coded rejection of this delivery.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushError"
                },
                "examples": {
                  "rejected": {
                    "summary": "Encounter closed",
                    "externalValue": "examples/push-rejected.json"
                  }
                }
              }
            }
          }
        },
        "x-poieti-response-classification": [
          {
            "status": [
              "202"
            ],
            "body": "any",
            "outcome": "accepted",
            "then": "poll GET /deliveries/{deliveryId}"
          },
          {
            "status": [
              "2XX"
            ],
            "body": "PushWriteResponse",
            "outcome": "written"
          },
          {
            "status": [
              "409"
            ],
            "body": "PushDuplicateDelivery",
            "outcome": "written"
          },
          {
            "status": [
              "4XX"
            ],
            "except": [
              "401",
              "403",
              "407",
              "408",
              "409",
              "425",
              "429"
            ],
            "body": "PushError",
            "outcome": "failed",
            "note": "retryable only when the body says retryable: true"
          },
          {
            "status": [
              "other"
            ],
            "body": "any",
            "outcome": "endpoint-suspect",
            "note": "network errors, timeouts, 3xx, 5xx, 401/403/407/408/425/429, other 409s, uncoded 4xx, invalid bodies and bodies over 64 KB. 401 and 403 defer the delivery (attempt not counted) and open the circuit until the endpoint configuration changes. For the rest the gateway probes GET /health: failing → deferred (attempt not counted, circuit opens; a 401 or 403 from /health counts as refused credentials, as for the delivery); passing → network errors, timeouts, 5xx and 408/425/429 retry per delivery then HIS_UNREACHABLE, others fail HIS_REJECTED."
          }
        ]
      }
    },
    "/deliveries/{deliveryId}": {
      "servers": [
        {
          "url": "{baseUrl}",
          "description": "The hospital endpoint configured with `set-his-endpoint` (public HTTPS, no query or fragment).",
          "variables": {
            "baseUrl": {
              "default": "https://his.example.org/poieti/v1"
            }
          }
        }
      ],
      "parameters": [
        {
          "$ref": "#/components/parameters/DeliveryId"
        }
      ],
      "get": {
        "operationId": "pushDeliveryStatus",
        "tags": [
          "Hospital push API"
        ],
        "summary": "Status of a queued delivery (implemented by the hospital)",
        "description": "Polled after a 202. 404 always means the hospital does not know the deliveryId: Poieti posts it again with the same key.",
        "security": [
          {
            "poietiSignature": []
          },
          {
            "poietiSignature": [],
            "hospitalBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/UserAgent"
          }
        ],
        "responses": {
          "200": {
            "description": "Written.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushWriteResponse"
                },
                "examples": {
                  "written": {
                    "summary": "Written",
                    "externalValue": "examples/push-written.json"
                  }
                }
              }
            }
          },
          "202": {
            "description": "Still processing. The body is ignored."
          },
          "404": {
            "description": "Unknown deliveryId; Poieti posts it again."
          },
          "422": {
            "description": "Coded rejection.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushError"
                },
                "examples": {
                  "rejected": {
                    "summary": "Encounter closed",
                    "externalValue": "examples/push-rejected.json"
                  }
                }
              }
            }
          }
        },
        "x-poieti-response-classification": [
          {
            "status": [
              "200"
            ],
            "body": "PushWriteResponse",
            "outcome": "written"
          },
          {
            "status": [
              "202"
            ],
            "body": "any",
            "outcome": "processing"
          },
          {
            "status": [
              "404"
            ],
            "body": "any",
            "outcome": "post-again"
          },
          {
            "status": [
              "4XX"
            ],
            "except": [
              "401",
              "403",
              "407",
              "408",
              "409",
              "425",
              "429"
            ],
            "body": "PushError",
            "outcome": "failed"
          },
          {
            "status": [
              "other"
            ],
            "body": "any",
            "outcome": "endpoint-suspect"
          }
        ]
      }
    },
    "/health": {
      "servers": [
        {
          "url": "{baseUrl}",
          "description": "The hospital endpoint configured with `set-his-endpoint` (public HTTPS, no query or fragment).",
          "variables": {
            "baseUrl": {
              "default": "https://his.example.org/poieti/v1"
            }
          }
        }
      ],
      "get": {
        "operationId": "pushHealth",
        "tags": [
          "Hospital push API"
        ],
        "summary": "Endpoint probe (implemented by the hospital)",
        "description": "Signed like every request. Poieti probes before charging an endpoint-suspect response to a delivery, while the circuit is open, and, while it is open, as soon as it sees the endpoint configuration changed. Answer 401 or 403 when the signature (or bearer token) is refused: Poieti then stops probing until the endpoint configuration changes.",
        "security": [
          {
            "poietiSignature": []
          },
          {
            "poietiSignature": [],
            "hospitalBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/UserAgent"
          }
        ],
        "responses": {
          "200": {
            "description": "Healthy.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushHealth"
                }
              }
            }
          }
        }
      }
    },
    "/census/wards/{wardCode}": {
      "servers": [
        {
          "url": "{baseUrl}",
          "description": "The hospital endpoint configured with `set-his-endpoint` (public HTTPS, no query or fragment).",
          "variables": {
            "baseUrl": {
              "default": "https://his.example.org/poieti/v1"
            }
          }
        }
      ],
      "parameters": [
        {
          "$ref": "#/components/parameters/WardCode"
        }
      ],
      "get": {
        "operationId": "pushCensus",
        "tags": [
          "Hospital push API"
        ],
        "summary": "Ward census for Poieti to fetch (implemented by the hospital)",
        "description": "Fetched every `census_interval_minutes` for each configured ward while census is enabled (0: never; the hospital may upload instead). Every valid snapshot is applied; applying writes only what changed.",
        "security": [
          {
            "poietiSignature": []
          },
          {
            "poietiSignature": [],
            "hospitalBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/UserAgent"
          }
        ],
        "responses": {
          "200": {
            "description": "Snapshot (at most 2 MB).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CensusSnapshotV1"
                },
                "examples": {
                  "context": {
                    "summary": "With clinical context",
                    "externalValue": "examples/census-snapshot-context.json"
                  }
                }
              }
            }
          }
        }
      }
    },
    "/patients/search": {
      "servers": [
        {
          "url": "{baseUrl}",
          "description": "The hospital endpoint configured with `set-his-endpoint` (public HTTPS, no query or fragment).",
          "variables": {
            "baseUrl": {
              "default": "https://his.example.org/poieti/v1"
            }
          }
        }
      ],
      "post": {
        "operationId": "pushPatientSearch",
        "tags": [
          "Hospital push API"
        ],
        "summary": "Look a patient up by chart number (implemented by the hospital)",
        "description": "Used by the nurse lookup when census is enabled. The chart number travels in the signed body, never in the URL. Return verification data only (no clinical context), at most 64 KB.",
        "security": [
          {
            "poietiSignature": []
          },
          {
            "poietiSignature": [],
            "hospitalBearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/UserAgent"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PatientSearchRequest"
              },
              "examples": {
                "lookup": {
                  "summary": "Lookup in ward 8B",
                  "externalValue": "examples/patient-search-request.json"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Matches (possibly none).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PatientSearchResponse"
                },
                "examples": {
                  "found": {
                    "summary": "One match",
                    "externalValue": "examples/patient-search-response.json"
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "webhooks": {
    "hisAlert": {
      "post": {
        "operationId": "hisAlert",
        "summary": "Alert webhook",
        "description": "Sent to the institution's alert webhook (a public notification service, never a hospital host) with a 5 s timeout, signed like push requests with the alert signing key; `target` is the webhook URL's path and query. Sent once per episode.",
        "security": [
          {
            "poietiSignature": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/UserAgent"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AlertV1"
              },
              "examples": {
                "paused": {
                  "summary": "Push paused",
                  "externalValue": "examples/alert.json"
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received."
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "poietiKey": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "phis.<env>.<hospitalId>.<credentialId>.<secret>",
        "description": "`Authorization: Bearer <key>` with a machine credential (see the PoietiKey schema). Credentials carry scopes (`deliveries`, `census`), an IP allowlist (or explicit any-address), optional census wards and an optional expiry. Verification happens in the database on every request, so revocation takes effect on the next request. Limit: 120 requests per minute per credential."
      },
      "poietiSignature": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Poieti-Signature",
        "description": "`t=<unix seconds>,v1=<hex HMAC-SHA256>` and, during a signing-key rotation overlap, a second `v1` made with the previous key (current key first). The HMAC input is `\"poieti-his/1\\n\" + t + \"\\n\" + METHOD + \"\\n\" + target + \"\\n\" + rawBody`, where `target` is the request path and query relative to the endpoint base URL (for base `https://his.example.org/poieti/v1` and URL `https://his.example.org/poieti/v1/census/wards/8B`, target is `/census/wards/8B`) and `rawBody` is the exact body bytes (empty for GET). The HMAC key is the signing key's ASCII text (43 base64url characters), not its decoded bytes. Verify every `v1` in constant time against your current and previous keys, accept if any matches, and reject when |now − t| > 300 seconds. `signature-vectors.json` holds test vectors."
      },
      "hospitalBearer": {
        "type": "http",
        "scheme": "bearer",
        "description": "Endpoint token configured with `set-his-endpoint` (auth type `bearer`); sent in addition to the signature."
      }
    },
    "schemas": {
      "Timestamp": {
        "type": "string",
        "format": "date-time",
        "description": "RFC 3339 date-time with an explicit offset. Metadata times from Poieti are UTC (`Z`, millisecond precision); record times in DeliveryV1 use the mapping timezone (default Asia/Taipei, `+08:00`). Times sent to Poieti must carry an offset."
      },
      "HisMode": {
        "enum": [
          "off",
          "push"
        ],
        "description": "Per-institution connection mode."
      },
      "DeliveryState": {
        "enum": [
          "blocked",
          "pending",
          "leased",
          "written",
          "failed",
          "superseded",
          "voided"
        ],
        "description": "`written`, `superseded` and `voided` are terminal. `failed` is terminal for automatic processing; a console retry (same deliveryId) or a nurse resend (new deliveryId) reopens it."
      },
      "DeliveryKind": {
        "enum": [
          "create",
          "correction"
        ],
        "description": "Resolved when Poieti first sends the delivery and never changed. A correction is a full replacement of the HIS record named by `supersedes.hisRecordId`."
      },
      "Code": {
        "type": "string",
        "pattern": "^[A-Z][A-Z0-9_]{1,63}$",
        "description": "Upper-case error or reason code."
      },
      "BlockReason": {
        "enum": [
          "CLIENT_UNVERIFIED",
          "IDENTITY_UNVERIFIED",
          "PATIENT_REQUIRED",
          "ENCOUNTER_REQUIRED",
          "CHART_NUMBER_INVALID",
          "ENCOUNTER_INVALID",
          "STAFF_NUMBER_REQUIRED",
          "MAPPING_UNAVAILABLE",
          "VALUE_UNMAPPABLE",
          "VALUE_TOO_LONG",
          "VALUE_UNENCODABLE",
          "PARTIAL_DATE_UNSUPPORTED",
          "VALUE_OUT_OF_RANGE"
        ],
        "description": "Why Poieti holds a delivery. A held delivery is never offered to the hospital."
      },
      "HisRecordId": {
        "type": "string",
        "minLength": 1,
        "maxLength": 128,
        "pattern": "^[^\\u0000-\\u001f\\u007f]+$",
        "description": "The hospital's identifier for the written HIS record, stored verbatim."
      },
      "WardCode": {
        "type": "string",
        "pattern": "^(?!\\.{1,2}$)[A-Za-z0-9_.-]{1,32}$",
        "description": "HIS ward code (`wards.his_code`). `.` and `..` are not ward codes."
      },
      "PoietiKey": {
        "type": "string",
        "pattern": "^phis\\.(dev|prod)\\.[a-z0-9][a-z0-9_-]{0,63}\\.[a-z2-7]{16}\\.[A-Za-z0-9_-]{43}$",
        "description": "Machine credential `phis.<env>.<hospitalId>.<credentialId>.<secret>`: `env` is `dev` or `prod`; `credentialId` is 16 lower-case RFC 4648 base32 characters; `secret` is 32 random bytes in unpadded base64url. Poieti stores only the SHA-256 of the secret's ASCII text. Treat the whole key as a password: read it from an environment variable or a file with restricted permissions, never from command-line arguments."
      },
      "Error": {
        "type": "object",
        "properties": {
          "error": {
            "type": "string",
            "minLength": 1,
            "description": "English display message. Behavior depends on `code`, never on this text."
          },
          "code": {
            "$ref": "#/components/schemas/Code"
          },
          "requestId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 128,
            "description": "Quote this when contacting Poieti."
          }
        },
        "required": [
          "error",
          "code",
          "requestId"
        ],
        "additionalProperties": false
      },
      "MappingRef": {
        "type": "object",
        "properties": {
          "featureId": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9-]{0,63}$"
          },
          "templateVersion": {
            "type": "integer",
            "minimum": 1
          },
          "mappingId": {
            "type": "string",
            "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$"
          },
          "version": {
            "type": "integer",
            "minimum": 1
          }
        },
        "required": [
          "featureId",
          "templateVersion",
          "mappingId",
          "version"
        ],
        "additionalProperties": false
      },
      "IntegrationResponse": {
        "type": "object",
        "properties": {
          "institutionId": {
            "type": "string",
            "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$"
          },
          "mode": {
            "$ref": "#/components/schemas/HisMode"
          },
          "paused": {
            "type": "boolean",
            "description": "While paused, Poieti sends nothing to the endpoint; confirmed records keep queueing."
          },
          "features": {
            "type": "array",
            "items": {
              "type": "string",
              "pattern": "^[a-z][a-z0-9-]{0,63}$"
            },
            "uniqueItems": true
          },
          "mappings": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MappingRef"
            }
          },
          "census": {
            "type": "boolean",
            "description": "Census uploads are accepted."
          },
          "serverTime": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "required": [
          "institutionId",
          "mode",
          "paused",
          "features",
          "mappings",
          "census",
          "serverTime"
        ],
        "additionalProperties": false
      },
      "StaffRef": {
        "type": "object",
        "description": "`staffNumber` is the hospital employee number set by Poieti staff; null when the institution does not require it and none is set, and for the `family-intake` system account, which can be the author and last editor of a record staged from the family's entries. `confirmedBy` is always a person.",
        "properties": {
          "poietiUserId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 128
          },
          "staffNumber": {
            "anyOf": [
              {
                "type": "string",
                "minLength": 1,
                "maxLength": 32
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "poietiUserId",
          "staffNumber"
        ],
        "additionalProperties": false
      },
      "PartialDate": {
        "type": "object",
        "description": "Only in `poieti-canonical` mappings; hospital mappings render partial dates as strings.",
        "properties": {
          "year": {
            "type": "integer"
          },
          "month": {
            "type": "integer",
            "minimum": 1,
            "maximum": 12
          },
          "day": {
            "type": "integer",
            "minimum": 1,
            "maximum": 31
          }
        },
        "required": [],
        "additionalProperties": false
      },
      "FieldScalar": {
        "anyOf": [
          {
            "type": "string"
          },
          {
            "type": "number"
          },
          {
            "type": "boolean"
          },
          {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          {
            "$ref": "#/components/schemas/PartialDate"
          }
        ]
      },
      "FieldValue": {
        "anyOf": [
          {
            "$ref": "#/components/schemas/FieldScalar"
          },
          {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": {
                "$ref": "#/components/schemas/FieldScalar"
              }
            },
            "description": "Repeatable rows (`rows` encoding). The row set replaces the stored rows as a whole."
          }
        ],
        "description": "In a hospital mapping every rendered scalar is a JSON string and absent values are omitted (never null, never defaulted). `poieti-canonical` keeps stored JSON types."
      },
      "DeliveryPatient": {
        "type": "object",
        "description": "Identity snapshot. A `create` matches on medicalRecordNumber + encounterId; a `correction` carries the identity of the record it replaces (the original admission, which may be closed). `displayName`, `wardCode` and `bed` are for verification only.",
        "properties": {
          "medicalRecordNumber": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "病歷號."
          },
          "encounterId": {
            "anyOf": [
              {
                "type": "string",
                "minLength": 1,
                "maxLength": 64,
                "description": "住院號 (the record's stay pin)."
              },
              {
                "type": "null"
              }
            ]
          },
          "hisPatientId": {
            "anyOf": [
              {
                "type": "string",
                "minLength": 1,
                "maxLength": 64
              },
              {
                "type": "null"
              }
            ]
          },
          "displayName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Verification only."
          },
          "wardCode": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/WardCode"
              },
              {
                "type": "null"
              }
            ]
          },
          "bed": {
            "anyOf": [
              {
                "type": "string",
                "minLength": 1,
                "maxLength": 32,
                "description": "Verification only."
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "medicalRecordNumber",
          "encounterId",
          "hisPatientId",
          "displayName",
          "wardCode",
          "bed"
        ],
        "additionalProperties": false
      },
      "Supersedes": {
        "type": "object",
        "description": "The written delivery this correction replaces.",
        "properties": {
          "deliveryId": {
            "type": "string",
            "format": "uuid"
          },
          "recordVersion": {
            "type": "integer",
            "minimum": 1
          },
          "hisRecordId": {
            "$ref": "#/components/schemas/HisRecordId"
          }
        },
        "required": [
          "deliveryId",
          "recordVersion",
          "hisRecordId"
        ],
        "additionalProperties": false
      },
      "MissingRequiredField": {
        "type": "object",
        "properties": {
          "field": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Poieti field id."
          },
          "target": {
            "anyOf": [
              {
                "type": "string",
                "minLength": 1,
                "maxLength": 128,
                "description": "Hospital field code, when mapped."
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "field",
          "target"
        ],
        "additionalProperties": false
      },
      "DeliveryAttachment": {
        "type": "object",
        "description": "Push requests carry no bytes: fetch them with `GET /his/v1/deliveries/{deliveryId}/attachments/{attachmentId}` and a `deliveries`-scope credential from an allowed address, while the delivery is leased (during the POST, or held by an accepted 202) or written, and verify size and hash before writing.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "mimeType": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "size": {
            "type": "integer",
            "minimum": 0
          },
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Lower-case hex SHA-256 of the bytes, when known."
          }
        },
        "required": [
          "id",
          "mimeType",
          "size"
        ],
        "additionalProperties": false
      },
      "DeliveryV1": {
        "type": "object",
        "properties": {
          "schema": {
            "const": "poieti.his.delivery/1"
          },
          "deliveryId": {
            "type": "string",
            "format": "uuid",
            "description": "Idempotency key. Deduplicate HIS writes on this value only, in both modes."
          },
          "generation": {
            "type": "integer",
            "minimum": 1,
            "description": "A nurse resend after a hospital identity rejection, or a redelivery, creates a new generation with a new deliveryId. A console retry, or a nurse's send of a held delivery never offered to the hospital, keeps the deliveryId and generation."
          },
          "kind": {
            "$ref": "#/components/schemas/DeliveryKind"
          },
          "institutionId": {
            "type": "string",
            "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$"
          },
          "feature": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "pattern": "^[a-z][a-z0-9-]{0,63}$"
              },
              "templateVersion": {
                "type": "integer",
                "minimum": 1
              },
              "title": {
                "type": "string",
                "minLength": 1,
                "maxLength": 200
              }
            },
            "required": [
              "id",
              "templateVersion",
              "title"
            ],
            "additionalProperties": false
          },
          "mapping": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$"
              },
              "version": {
                "type": "integer",
                "minimum": 1
              }
            },
            "required": [
              "id",
              "version"
            ],
            "additionalProperties": false
          },
          "target": {
            "type": "object",
            "properties": {
              "form": {
                "type": "string",
                "minLength": 1,
                "maxLength": 128
              },
              "formVersion": {
                "type": "string",
                "minLength": 1,
                "maxLength": 64
              },
              "charset": {
                "enum": [
                  "utf-8",
                  "cp950"
                ],
                "description": "Every string was checked to be encodable in this charset."
              }
            },
            "required": [
              "form",
              "formVersion",
              "charset"
            ],
            "additionalProperties": false
          },
          "record": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "version": {
                "type": "integer",
                "minimum": 1
              },
              "observedAt": {
                "$ref": "#/components/schemas/Timestamp",
                "description": "Clinical event time from the mapping's observedAt fields; omitted when unknown."
              },
              "confirmedAt": {
                "$ref": "#/components/schemas/Timestamp"
              },
              "author": {
                "$ref": "#/components/schemas/StaffRef"
              },
              "lastEditedBy": {
                "$ref": "#/components/schemas/StaffRef"
              },
              "confirmedBy": {
                "$ref": "#/components/schemas/StaffRef"
              }
            },
            "required": [
              "id",
              "version",
              "confirmedAt",
              "author",
              "lastEditedBy",
              "confirmedBy"
            ],
            "additionalProperties": false
          },
          "supersedes": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/Supersedes"
              },
              {
                "type": "null"
              }
            ]
          },
          "patient": {
            "$ref": "#/components/schemas/DeliveryPatient"
          },
          "fields": {
            "type": "object",
            "propertyNames": {
              "minLength": 1,
              "maxLength": 128
            },
            "additionalProperties": {
              "$ref": "#/components/schemas/FieldValue"
            },
            "description": "Hospital field code → rendered value, from the reviewed mapping. In a hospital mapping, text is sent in Unicode NFC (composed form; CJK compatibility ideographs stay as typed), as its length and character-set limits are measured, and a joined value names each code once."
          },
          "missingRequired": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MissingRequiredField"
            },
            "description": "Applicable required fields without a value. Informational: Poieti still delivers."
          },
          "notSent": {
            "type": "array",
            "items": {
              "type": "string",
              "minLength": 1,
              "maxLength": 200
            },
            "description": "Poieti field ids that have values but are excluded by the mapping."
          },
          "attachments": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DeliveryAttachment"
            }
          }
        },
        "required": [
          "schema",
          "deliveryId",
          "generation",
          "kind",
          "institutionId",
          "feature",
          "mapping",
          "target",
          "record",
          "supersedes",
          "patient",
          "fields",
          "missingRequired",
          "notSent",
          "attachments"
        ],
        "additionalProperties": false,
        "description": "One confirmed record version, rendered through the reviewed mapping. The body of `POST /deliveries`. The body for a deliveryId is identical on every attempt and retry; counters travel beside it. Evidence quotes, source references and conversation ids are never included. Poieti sends exactly these members; receivers should still ignore members they do not know.",
        "if": {
          "properties": {
            "kind": {
              "const": "correction"
            }
          }
        },
        "then": {
          "properties": {
            "supersedes": {
              "$ref": "#/components/schemas/Supersedes"
            }
          }
        },
        "else": {
          "properties": {
            "supersedes": {
              "type": "null"
            }
          }
        }
      },
      "DeliveryError": {
        "type": "object",
        "properties": {
          "code": {
            "$ref": "#/components/schemas/Code"
          },
          "message": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500
          },
          "retryable": {
            "type": "boolean"
          }
        },
        "required": [
          "code",
          "retryable"
        ],
        "additionalProperties": false
      },
      "DeliveryStatus": {
        "type": "object",
        "description": "Delivery metadata for diagnosis and reconciliation. Never contains identity or clinical values.",
        "properties": {
          "deliveryId": {
            "type": "string",
            "format": "uuid"
          },
          "generation": {
            "type": "integer",
            "minimum": 1
          },
          "featureId": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9-]{0,63}$"
          },
          "recordId": {
            "type": "string",
            "format": "uuid"
          },
          "recordVersion": {
            "type": "integer",
            "minimum": 1
          },
          "state": {
            "$ref": "#/components/schemas/DeliveryState"
          },
          "kind": {
            "$ref": "#/components/schemas/DeliveryKind",
            "description": "Absent until Poieti first sends the delivery."
          },
          "blockReasons": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BlockReason"
            },
            "description": "Non-empty exactly when state is `blocked`."
          },
          "hisRecordId": {
            "$ref": "#/components/schemas/HisRecordId"
          },
          "error": {
            "$ref": "#/components/schemas/DeliveryError"
          },
          "attempts": {
            "type": "integer",
            "minimum": 0,
            "description": "Attempts so far, counting expired leases."
          },
          "leaseExpiresAt": {
            "$ref": "#/components/schemas/Timestamp",
            "description": "Present while leased."
          },
          "acceptedAt": {
            "$ref": "#/components/schemas/Timestamp",
            "description": "Present while an accepted 202 holds the lease."
          },
          "createdAt": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "updatedAt": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "writtenAt": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "required": [
          "deliveryId",
          "generation",
          "featureId",
          "recordId",
          "recordVersion",
          "state",
          "blockReasons",
          "attempts",
          "createdAt",
          "updatedAt"
        ],
        "additionalProperties": false
      },
      "DeliveryListResponse": {
        "type": "object",
        "description": "Ordered by `updatedAt`, then `deliveryId`, ascending.",
        "properties": {
          "deliveries": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DeliveryStatus"
            },
            "maxItems": 200
          },
          "nextAfter": {
            "anyOf": [
              {
                "type": "string",
                "pattern": "^[A-Za-z0-9_-]{1,200}$",
                "description": "Pass as `after` for the next page. Present whenever a page is full, so the next page may be empty; null on a short page."
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "deliveries",
          "nextAfter"
        ],
        "additionalProperties": false
      },
      "HisContextItem": {
        "type": "object",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_.:-]{1,64}$",
            "description": "Unique per patient and kind."
          },
          "label": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 1000
          },
          "value": {
            "type": "number"
          },
          "unit": {
            "type": "string",
            "minLength": 1,
            "maxLength": 32
          },
          "observedAt": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "required": [
          "code",
          "label"
        ],
        "additionalProperties": false,
        "dependentRequired": {
          "value": [
            "unit"
          ],
          "unit": [
            "value"
          ]
        },
        "not": {
          "required": [
            "text",
            "value"
          ]
        },
        "description": "Clinical context item: `{text}` or `{value, unit}`."
      },
      "HisPatient": {
        "type": "object",
        "description": "A patient as the HIS reports it. In a census snapshot the ward is the path and `wardCode` is not allowed; in patient search results `wardCode` is required and clinical context is not allowed.",
        "properties": {
          "medicalRecordNumber": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "病歷號; Poieti normalizes (NFKC, trim, upper-case) and checks the institution's pattern."
          },
          "encounterId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "住院號 of the current admission."
          },
          "hisPatientId": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "displayName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "wardCode": {
            "$ref": "#/components/schemas/WardCode"
          },
          "bed": {
            "type": "string",
            "maxLength": 32,
            "description": "Sent when the HIS manages beds; Poieti then treats the bed as HIS-managed."
          },
          "admittedAt": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "discharged": {
            "type": "boolean",
            "description": "Explicit discharge. Absence from a snapshot never discharges."
          },
          "allergies": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/HisContextItem"
            },
            "maxItems": 100,
            "description": "Push mode only. Absent: not provided (stored rows kept). `[]`: the HIS has none."
          },
          "alerts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/HisContextItem"
            },
            "maxItems": 100,
            "description": "Push mode only; same semantics as allergies."
          },
          "vitals": {
            "type": "array",
            "items": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/HisContextItem"
                }
              ],
              "required": [
                "observedAt"
              ],
              "anyOf": [
                {
                  "required": [
                    "text"
                  ]
                },
                {
                  "required": [
                    "value"
                  ]
                }
              ]
            },
            "maxItems": 100,
            "description": "Push mode only; same semantics as allergies. Each vital carries its observation time."
          }
        },
        "required": [
          "medicalRecordNumber",
          "encounterId",
          "displayName"
        ],
        "additionalProperties": false
      },
      "CensusSnapshotV1": {
        "type": "object",
        "description": "One ward's patient list (at most 500 patients and 2 MB). Identity and admission data are accepted whenever census is enabled; `allergies`, `alerts` and `vitals` only in push mode.",
        "properties": {
          "asOf": {
            "$ref": "#/components/schemas/Timestamp",
            "description": "When the HIS took the snapshot. Must carry an offset, be at most 5 minutes ahead of server time and at most 24 hours old."
          },
          "complete": {
            "const": true,
            "description": "The snapshot lists every current patient of the ward."
          },
          "patients": {
            "type": "array",
            "maxItems": 500,
            "items": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/HisPatient"
                }
              ],
              "not": {
                "required": [
                  "wardCode"
                ]
              }
            },
            "description": "Chart numbers and encounter ids must not repeat."
          }
        },
        "required": [
          "asOf",
          "complete",
          "patients"
        ],
        "additionalProperties": false
      },
      "CensusRejection": {
        "type": "object",
        "properties": {
          "medicalRecordNumber": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "code": {
            "$ref": "#/components/schemas/Code",
            "description": "`IDENTITY_CONFLICT` (a manual patient with this chart number has a different encounter and name; nothing changed), `CHART_NUMBER_INVALID`, `ENCOUNTER_INVALID`, `ENCOUNTER_IN_USE` (another patient holds this encounter), `PATIENT_INVALID` (a required member is missing or too long, or a time has no offset) or `OUT_OF_SCOPE` (the credential's census wards do not include the ward the patient is in, or the ward of the patient holding this encounter; nothing changed). Readers should treat an unknown code as a rejection."
          }
        },
        "required": [
          "medicalRecordNumber",
          "code"
        ],
        "additionalProperties": false
      },
      "CensusResult": {
        "type": "object",
        "properties": {
          "created": {
            "type": "integer",
            "minimum": 0
          },
          "updated": {
            "type": "integer",
            "minimum": 0
          },
          "adopted": {
            "type": "integer",
            "minimum": 0,
            "description": "Manually added patients now managed by the HIS."
          },
          "transferred": {
            "type": "integer",
            "minimum": 0
          },
          "readmitted": {
            "type": "integer",
            "minimum": 0
          },
          "discharged": {
            "type": "integer",
            "minimum": 0
          },
          "unchanged": {
            "type": "integer",
            "minimum": 0
          },
          "missing": {
            "type": "integer",
            "minimum": 0,
            "description": "HIS patients of this ward absent from the snapshot; shown as 未出現在院方名單, never discharged."
          },
          "rejected": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CensusRejection"
            }
          },
          "replayed": {
            "type": "boolean",
            "description": "Same asOf and same content as the last applied snapshot, which rejected no entry; counts are zero. The same snapshot after one that rejected entries is applied again (replayed false)."
          }
        },
        "required": [
          "created",
          "updated",
          "adopted",
          "transferred",
          "readmitted",
          "discharged",
          "unchanged",
          "missing",
          "rejected",
          "replayed"
        ],
        "additionalProperties": false
      },
      "PatientSearchRequest": {
        "type": "object",
        "description": "A nurse lookup in push mode. Poieti sends it only for a ward the nurse belongs to and keeps results for that ward only.",
        "properties": {
          "schema": {
            "const": "poieti.his.patient-search/1"
          },
          "medicalRecordNumber": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "wardCode": {
            "$ref": "#/components/schemas/WardCode"
          },
          "requestedBy": {
            "$ref": "#/components/schemas/StaffRef"
          }
        },
        "required": [
          "schema",
          "medicalRecordNumber",
          "wardCode",
          "requestedBy"
        ],
        "additionalProperties": false
      },
      "PatientSearchResponse": {
        "type": "object",
        "properties": {
          "patients": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/HisPatient"
                }
              ],
              "required": [
                "wardCode"
              ],
              "not": {
                "anyOf": [
                  {
                    "required": [
                      "allergies"
                    ]
                  },
                  {
                    "required": [
                      "alerts"
                    ]
                  },
                  {
                    "required": [
                      "vitals"
                    ]
                  }
                ]
              }
            }
          }
        },
        "required": [
          "patients"
        ],
        "additionalProperties": false
      },
      "PushWriteResponse": {
        "type": "object",
        "description": "2xx body for a written delivery, including a repeat of an already written deliveryId (same hisRecordId).",
        "properties": {
          "hisRecordId": {
            "$ref": "#/components/schemas/HisRecordId"
          }
        },
        "required": [
          "hisRecordId"
        ],
        "additionalProperties": true
      },
      "PushError": {
        "type": "object",
        "description": "Coded rejection from the hospital endpoint. Poieti stores `code`, the first 500 characters of `message` and `retryable`; the rest of the body is never stored or logged.",
        "properties": {
          "code": {
            "$ref": "#/components/schemas/Code"
          },
          "message": {
            "type": "string",
            "maxLength": 500
          },
          "retryable": {
            "type": "boolean",
            "default": false
          },
          "hisRecordId": {
            "$ref": "#/components/schemas/HisRecordId"
          }
        },
        "required": [
          "code"
        ],
        "additionalProperties": true
      },
      "PushDuplicateDelivery": {
        "allOf": [
          {
            "$ref": "#/components/schemas/PushError"
          }
        ],
        "properties": {
          "code": {
            "const": "DUPLICATE_DELIVERY"
          }
        },
        "required": [
          "code",
          "hisRecordId"
        ],
        "description": "409 alternative to a 200 replay: the deliveryId is already written as `hisRecordId`."
      },
      "PushHealth": {
        "type": "object",
        "description": "Any 200 response passes; the body is ignored.",
        "properties": {
          "status": {
            "type": "string"
          }
        },
        "required": [],
        "additionalProperties": true
      },
      "AlertDetail": {
        "type": "object",
        "description": "Codes, counts and times only; never identity, field values or hospital text.",
        "properties": {
          "reason": {
            "enum": [
              "unreachable",
              "auth",
              "protocol"
            ]
          },
          "since": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "nextProbeAt": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "deliveryId": {
            "type": "string",
            "format": "uuid"
          },
          "featureId": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9-]{0,63}$"
          },
          "errorCode": {
            "$ref": "#/components/schemas/Code"
          },
          "errorOrigin": {
            "enum": [
              "poieti",
              "hospital"
            ],
            "description": "Whose errorCode is: the hospital's refusal (whatever it spells, even one of Poieti's codes), or Poieti's own (the delivery may be in the HIS). Absent for failures recorded before Poieti kept it."
          },
          "overdue": {
            "enum": [
              "accepted",
              "pending"
            ]
          },
          "count": {
            "type": "integer",
            "minimum": 0
          },
          "oldestAt": {
            "$ref": "#/components/schemas/Timestamp"
          }
        },
        "required": [],
        "additionalProperties": false
      },
      "AlertV1": {
        "type": "object",
        "description": "Alert webhook body (metadata only). `his.push.paused`: reason, since, nextProbeAt. `his.push.resumed`: since. `his.delivery.failed`: deliveryId, featureId, errorCode, errorOrigin. `his.delivery.overdue`: overdue, count, oldestAt.",
        "properties": {
          "schema": {
            "const": "poieti.his.alert/1"
          },
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "event": {
            "enum": [
              "his.push.paused",
              "his.push.resumed",
              "his.delivery.failed",
              "his.delivery.overdue"
            ]
          },
          "environment": {
            "enum": [
              "dev",
              "prod"
            ]
          },
          "institutionId": {
            "type": "string",
            "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$"
          },
          "at": {
            "$ref": "#/components/schemas/Timestamp"
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "One-line summary without patient data, for chat-style notification services."
          },
          "detail": {
            "$ref": "#/components/schemas/AlertDetail"
          }
        },
        "required": [
          "schema",
          "id",
          "event",
          "environment",
          "institutionId",
          "at",
          "text",
          "detail"
        ],
        "additionalProperties": false
      }
    },
    "parameters": {
      "DeliveryId": {
        "name": "deliveryId",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string",
          "format": "uuid"
        },
        "example": "3d2c1b0a-9f8e-4d7c-8b6a-5f4e3d2c1b0a"
      },
      "AttachmentId": {
        "name": "attachmentId",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string",
          "format": "uuid"
        },
        "example": "c4b3a291-8f7e-4d6c-9b5a-4e3d2c1b0a9f"
      },
      "WardCode": {
        "name": "wardCode",
        "in": "path",
        "required": true,
        "schema": {
          "$ref": "#/components/schemas/WardCode"
        },
        "example": "8B"
      },
      "State": {
        "name": "state",
        "in": "query",
        "required": false,
        "schema": {
          "$ref": "#/components/schemas/DeliveryState"
        },
        "example": "written"
      },
      "UpdatedSince": {
        "name": "updatedSince",
        "in": "query",
        "required": false,
        "description": "Only deliveries updated at or after this time. Ignored when `after` is given.",
        "schema": {
          "$ref": "#/components/schemas/Timestamp"
        },
        "example": "2026-10-16T00:00:00+08:00"
      },
      "After": {
        "name": "after",
        "in": "query",
        "required": false,
        "description": "`nextAfter` from the previous page.",
        "schema": {
          "type": "string",
          "pattern": "^[A-Za-z0-9_-]{1,200}$"
        }
      },
      "Limit": {
        "name": "limit",
        "in": "query",
        "required": false,
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 200,
          "default": 100
        }
      },
      "IdempotencyKey": {
        "name": "Idempotency-Key",
        "in": "header",
        "required": true,
        "description": "Always the deliveryId, on every attempt and console retry.",
        "schema": {
          "type": "string",
          "format": "uuid"
        },
        "example": "3d2c1b0a-9f8e-4d7c-8b6a-5f4e3d2c1b0a"
      },
      "PoietiDelivery": {
        "name": "X-Poieti-Delivery",
        "in": "header",
        "required": true,
        "description": "The deliveryId (equal to Idempotency-Key and the body's deliveryId).",
        "schema": {
          "type": "string",
          "format": "uuid"
        },
        "example": "3d2c1b0a-9f8e-4d7c-8b6a-5f4e3d2c1b0a"
      },
      "PoietiAttempt": {
        "name": "X-Poieti-Attempt",
        "in": "header",
        "required": true,
        "description": "Attempt number. Outside the body so every attempt sends identical body bytes.",
        "schema": {
          "type": "integer",
          "minimum": 1
        },
        "example": 1
      },
      "UserAgent": {
        "name": "User-Agent",
        "in": "header",
        "required": true,
        "schema": {
          "const": "Poieti-HIS/1"
        },
        "example": "Poieti-HIS/1"
      }
    },
    "headers": {
      "NoStore": {
        "description": "Always `no-store`.",
        "schema": {
          "const": "no-store"
        }
      },
      "RetryAfter": {
        "description": "Seconds to wait.",
        "schema": {
          "type": "integer",
          "minimum": 1
        }
      },
      "Digest": {
        "description": "`sha-256=<base64 of the SHA-256 digest>` (RFC 3230) when the hash is known; DeliveryV1 carries the same digest as lower-case hex.",
        "schema": {
          "type": "string",
          "pattern": "^sha-256=[A-Za-z0-9+/]{43}=$"
        }
      },
      "ContentLength": {
        "description": "Byte length; equals the attachment's `size`.",
        "schema": {
          "type": "integer",
          "minimum": 0
        }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Authentication failed.",
        "headers": {
          "Cache-Control": {
            "$ref": "#/components/headers/NoStore"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "HIS_UNAUTHORIZED": {
                "summary": "HIS_UNAUTHORIZED",
                "value": {
                  "error": "Unauthorized.",
                  "code": "HIS_UNAUTHORIZED",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              }
            }
          }
        }
      },
      "Forbidden": {
        "description": "The credential may not make this request.",
        "headers": {
          "Cache-Control": {
            "$ref": "#/components/headers/NoStore"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "HIS_IP_NOT_ALLOWED": {
                "summary": "HIS_IP_NOT_ALLOWED",
                "value": {
                  "error": "This address is not allowed for this credential.",
                  "code": "HIS_IP_NOT_ALLOWED",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              },
              "HIS_SCOPE_DENIED": {
                "summary": "HIS_SCOPE_DENIED",
                "value": {
                  "error": "This credential does not have the required scope.",
                  "code": "HIS_SCOPE_DENIED",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              }
            }
          }
        }
      },
      "RateLimited": {
        "description": "Rate limit reached.",
        "headers": {
          "Cache-Control": {
            "$ref": "#/components/headers/NoStore"
          },
          "Retry-After": {
            "$ref": "#/components/headers/RetryAfter"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "HIS_RATE_LIMITED": {
                "summary": "HIS_RATE_LIMITED",
                "value": {
                  "error": "Too many requests.",
                  "code": "HIS_RATE_LIMITED",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              }
            }
          }
        }
      },
      "RequestInvalid": {
        "description": "The request is invalid.",
        "headers": {
          "Cache-Control": {
            "$ref": "#/components/headers/NoStore"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "HIS_REQUEST_INVALID": {
                "summary": "HIS_REQUEST_INVALID",
                "value": {
                  "error": "Invalid request.",
                  "code": "HIS_REQUEST_INVALID",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              }
            }
          }
        }
      },
      "BodyTooLarge": {
        "description": "The request body is too large.",
        "headers": {
          "Cache-Control": {
            "$ref": "#/components/headers/NoStore"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "HIS_BODY_TOO_LARGE": {
                "summary": "HIS_BODY_TOO_LARGE",
                "value": {
                  "error": "The request body is too large.",
                  "code": "HIS_BODY_TOO_LARGE",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              }
            }
          }
        }
      },
      "DeliveryNotFound": {
        "description": "Unknown delivery.",
        "headers": {
          "Cache-Control": {
            "$ref": "#/components/headers/NoStore"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "DELIVERY_NOT_FOUND": {
                "summary": "DELIVERY_NOT_FOUND",
                "value": {
                  "error": "Delivery not found.",
                  "code": "DELIVERY_NOT_FOUND",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              }
            }
          }
        }
      },
      "InternalError": {
        "description": "Unexpected server failure; retry later.",
        "headers": {
          "Cache-Control": {
            "$ref": "#/components/headers/NoStore"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "HIS_INTERNAL_ERROR": {
                "summary": "HIS_INTERNAL_ERROR",
                "value": {
                  "error": "Something went wrong.",
                  "code": "HIS_INTERNAL_ERROR",
                  "requestId": "8c1f0a5e2b7d4c39a6e1"
                }
              }
            }
          }
        }
      }
    }
  }
}
