{
  "openapi": "3.1.0",
  "info": {
    "title": "AgriTrace HTTP API",
    "version": "1",
    "description": "The CropPath HTTP API, version 1, at https://txng.theio.vn. It covers a company's traceability records (growing areas, lots, packing, shipping and exports), devices and their signed messages, laboratories, the public lot and fruit pages behind the QR codes, and webhooks. Guides, examples and this reference: https://txng.theio.vn/en/developers.\n\nEach operation's `security` lists the credentials it accepts. `bearer`: an API token (`agt_...`, role tenant_admin, operator or auditor) or the access token of an OAuth2 API client (`ago_...`), sent as `Authorization: Bearer`; an API client also needs the scope the operation lists under `oauth2`. `cookie`: a person signed in to the CropPath console. An operation with no security is anonymous. `deviceMtls`: a device or gateway with its client certificate.\n\n`x-session-only: true` marks an operation for people signed in to the console only (account, team, credentials, company settings and support): it lists the session cookie as its only security. An API token or API client calling one is refused: 401 `not_authenticated` for the signed-in user's own operations under `/v1/auth/...` and for `GET /v1/help`, which read only the session cookie, and 403 `role_not_permitted` for the others. Operations for CropPath's platform admins and for lab users need a role that no API client and no API token a company creates can hold, so they answer 403 to a company's integrations as well.\n\nAn error answers with a stable `code` in its JSON body (an `Error`; device ingest answers an `IngestResult`, and the OAuth2 endpoints the RFC 6749 error with the `code` beside it). An operation that lists the `Idempotency-Key` header can be retried safely with the same key.\n\nPer-company quotas (#134): every call made with a company's API tokens or API clients counts toward that company's quotas, on top of the per-client limits an operation lists: calls per minute and calls per UTC day (the company admin's usage page and `getCompanyUsage` show both). Over either, any such operation answers 429 `too_many_requests` with `Retry-After` (for the daily quota, the seconds until the next UTC midnight), right after the credential is checked and before anything else is checked or changed.",
    "x-sdk-description": "The CropPath HTTP API, version 1, at https://txng.theio.vn. It covers a company's traceability records (growing areas, lots, packing, shipping and exports), devices and their signed messages, laboratories, the public lot and fruit pages behind the QR codes, and webhooks. Guides, examples and this reference: https://txng.theio.vn/en/developers.\n\nEach operation's `security` lists the credentials it accepts. `bearer`: an API token (`agt_...`, role tenant_admin, operator or auditor) or the access token of an OAuth2 API client (`ago_...`), sent as `Authorization: Bearer`; an API client also needs the scope the operation lists under `oauth2`. `cookie`: a person signed in to the CropPath console. An operation with no security is anonymous. `deviceMtls`: a device or gateway with its client certificate.\n\n`x-session-only: true` marks an operation for people signed in to the console only (account, team, credentials, company settings and support): it lists the session cookie as its only security. An API token or API client calling one is refused: 401 `not_authenticated` for the signed-in user's own operations under `/v1/auth/...` and for `GET /v1/help`, which read only the session cookie, and 403 `role_not_permitted` for the others. Operations for CropPath's platform admins and for lab users need a role that no API client and no API token a company creates can hold, so they answer 403 to a company's integrations as well.\n\nAn error answers with a stable `code` in its JSON body (an `Error`; device ingest answers an `IngestResult`, and the OAuth2 endpoints the RFC 6749 error with the `code` beside it). An operation that lists the `Idempotency-Key` header can be retried safely with the same key."
  },
  "servers": [
    {
      "url": "https://txng.theio.vn",
      "description": "CropPath production."
    }
  ],
  "tags": [
    {
      "name": "agronomy",
      "description": "#351: the agronomist registry, the agronomic input sheets and their signatures, and the agronomist's home (console API, not in the partner SDK clients)."
    },
    {
      "name": "alarms",
      "description": "#361: the irrigation alarms of a company (ADR 0015, the alarm philosophy): list, read, acknowledge, shelve and unshelve (console API, not in the partner SDK clients)."
    },
    {
      "name": "attachments",
      "description": "Evidence files (audio, images and PDF documents) stored under their SHA-256: a company uploads and reads them, and a device uploads the attachments its signed messages name."
    },
    {
      "name": "audit",
      "description": "The company's activity log: who changed what and when, with filters and a CSV download."
    },
    {
      "name": "auth",
      "description": "Signing in and the signed-in account: login with two-step sign-in, sessions, password, one-time account links, and the OAuth2 token and revocation endpoints of API clients."
    },
    {
      "name": "broker",
      "description": "Used by CropPath's MQTT broker to ask whether a device may publish or subscribe. Not for partner integrations."
    },
    {
      "name": "control",
      "description": "Irrigation control (#352): the controllers' zones, the schedule and threshold rules bound to a signed agronomic input sheet, and the programs the engine composes, approved by a person and sent through the signed command channel."
    },
    {
      "name": "devices",
      "description": "The company's devices, gateways and signing keys, device commands, the harvest app's key registrations, and CropPath's approval of devices and gateways."
    },
    {
      "name": "envelopes",
      "description": "The signed device messages the company has stored: a list, one message, and a live stream."
    },
    {
      "name": "ingest",
      "description": "Devices and gateways send their signed messages here, over mutual TLS."
    },
    {
      "name": "integrity",
      "description": "Alerts, device messages held for review and the review decision, and the harvest volume declared for a growing area across companies."
    },
    {
      "name": "labs",
      "description": "Testing laboratories: the lab registry and lab keys, a lab's approvals for destination markets, its sample assignments and signed results, and the maximum residue limits results are judged against."
    },
    {
      "name": "lots",
      "description": "Lots, measurement sessions and fruits, grading rules, samples for lab tests, the lot's trust, close checks, and recall."
    },
    {
      "name": "ops",
      "description": "Health and metrics of the service."
    },
    {
      "name": "packing",
      "description": "Cartons and their contents, the lot's pack seal, harvest declarations and the mass balance of a growing area, and export labels with their templates."
    },
    {
      "name": "public",
      "description": "Anonymous reads behind the QR codes: public lot and fruit records with their credentials and EPCIS documents, the customs dossier, code resolution, a facility's DID document, reports from the public, and the daily integrity anchors."
    },
    {
      "name": "registry",
      "description": "Companies, facilities and facility proposals, growing areas with their certifications, satellite checks and sprays, growers, facility issuer keys, the authorities' published code lists, first-admin invitations and company offboarding."
    },
    {
      "name": "reports",
      "description": "Reports the public filed about the company's fruits: the list, one report with its scan history, and resolving it."
    },
    {
      "name": "sandbox",
      "description": "The hosted sandbox only: `x-sandbox-only: true` marks its operations, which answer 404 `no_such_route` on every other deployment, exactly like an unknown path. A partner creates a throwaway demo company and a 24-hour API token for it, without an account."
    },
    {
      "name": "settings",
      "description": "Company settings for its people: profile and logo, members and invitations, the two-step sign-in rule, API tokens and API clients, usage, the getting-started checklist, notifications, personal data requests, the full data export and the offboarding state."
    },
    {
      "name": "shipping",
      "description": "Shipments: the lots they carry, temperature logger readings, the consignee and document references, and the departure."
    },
    {
      "name": "support",
      "description": "The help page and status page, support requests to CropPath, and platform announcements."
    },
    {
      "name": "traceability",
      "description": "Traceability records of a lot or of the company: EPCIS 2.0 documents and stored events, FSMA 204 CSV, recall and records-request exports, and EPCIS capture from partner systems."
    },
    {
      "name": "webhooks",
      "description": "Webhook subscriptions that notify a partner's endpoint of events, with their delivery log and redelivery."
    }
  ],
  "paths": {
    "/healthz": {
      "get": {
        "operationId": "getHealth",
        "summary": "Liveness and operational status",
        "description": "Unauthenticated. Reports the outbound backlog per target, the watched certificates and, when the MQTT bridge runs, its connection state. In the read-only maintenance mode of the PostgreSQL cutover (#123) it also reports `read_only`; every other method of every route, and every audited read (the exports), then answers 503 with Retry-After.",
        "tags": [
          "ops"
        ],
        "security": [],
        "responses": {
          "200": {
            "description": "The service is up.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Health"
                },
                "example": {
                  "ok": true,
                  "outbound_backlog": {
                    "national": 0
                  },
                  "certificates": []
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/alerts": {
      "get": {
        "operationId": "listAlerts",
        "summary": "Alerts of the tenant",
        "description": "Up to `limit` alerts (default and most 200), newest first. Open alerts only unless `all=1`. A platform admin also gets the platform alerts that belong to no tenant (`tenant` null), such as `facility_code_conflict` from the facility backfill. B9 (#21): `kind`, `severity` and `device_id` keep the alerts equal to each one given; when more alerts follow, the `X-Next-Cursor` header carries the next page's `cursor` (the body stays an array). These parameters and the header are not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before them, and the 400 response keeps its 0.2.0 form: a bad `kind`, `severity`, `device_id`, `limit` or `cursor` also answers 400 (`bad_kind`, `bad_severity`, `bad_device_id`, `bad_limit`, `bad_cursor`).",
        "tags": [
          "integrity"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "all",
            "in": "query",
            "required": false,
            "description": "`1` includes resolved alerts; any other value or none returns open alerts only.",
            "schema": {
              "type": "string"
            },
            "example": "1"
          },
          {
            "name": "kind",
            "in": "query",
            "required": false,
            "description": "Only alerts of this kind (`seq_gap`, `quarantined`, `label_clone_suspected`, ...).",
            "schema": {
              "type": "string",
              "pattern": "^[a-z0-9_]{1,64}$"
            },
            "example": "seq_gap",
            "x-not-in-sdk": true
          },
          {
            "name": "severity",
            "in": "query",
            "required": false,
            "description": "Only alerts of this severity (`info`, `warning`, `high`).",
            "schema": {
              "type": "string",
              "pattern": "^[a-z]{1,32}$"
            },
            "example": "high",
            "x-not-in-sdk": true
          },
          {
            "name": "device_id",
            "in": "query",
            "required": false,
            "description": "Only alerts about this device.",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128
            },
            "example": "scale-1",
            "x-not-in-sdk": true
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size: 1 to 200 alerts (default 200).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 200
            },
            "example": 200,
            "x-not-in-sdk": true
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `X-Next-Cursor` header.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjd9",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "Alerts.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Next-Cursor": {
                "description": "The `cursor` of the next page, sent only when more alerts follow.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/Alert"
                  }
                },
                "example": [
                  {
                    "id": 7,
                    "tenant": "coop-dl",
                    "kind": "quarantined",
                    "severity": "warning",
                    "device_id": "scale-1",
                    "envelope_id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                    "detail": {
                      "reasons": [
                        "volume_exceeds_cap"
                      ]
                    },
                    "created_at": 1790000000.5,
                    "resolved_at": null
                  }
                ]
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Up to 200 alerts, newest first. Open alerts only unless `all=1`. A platform admin also gets the platform alerts that belong to no tenant (`tenant` null), such as `facility_code_conflict` from the facility backfill."
      }
    },
    "/v1/alerts/{id}/resolve": {
      "post": {
        "operationId": "resolveAlert",
        "summary": "Resolve an alert",
        "description": "B9 (#21): resolves one alert by hand, with an optional note. Idempotent: an alert already resolved is answered as it is (200, its first `resolved_at`) and nothing changes. Audited (`alert.resolve`, in the same transaction, also for an alert already resolved, with `already_resolved`; the note is kept in the audit row, the alert has no field for it). Allowed for tenant_admin and platform_admin acting for the tenant; a platform admin also resolves the platform alerts that belong to no tenant (`tenant` null), whose audit row belongs to no company. Another tenant's alert answers like a missing one. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "integrity"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "review"
            ]
          }
        ],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The alert id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AlertResolution"
              },
              "example": {
                "note": "Scale replaced; the missing readings were re-entered by hand."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The alert, resolved (or as it was, when it already was).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Alert"
                },
                "example": {
                  "id": 7,
                  "tenant": "coop-dl",
                  "kind": "seq_gap",
                  "severity": "warning",
                  "device_id": "scale-1",
                  "envelope_id": null,
                  "detail": {
                    "from": 4,
                    "to": 6
                  },
                  "created_at": 1790000000.5,
                  "resolved_at": 1790003600.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a note that is not a string of at most 500 characters, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: reason",
                      "code": "unknown_fields"
                    }
                  },
                  "note": {
                    "value": {
                      "error": "note must be a string of at most 500 characters",
                      "code": "note_must_be_a_string_of_at_most_500_characters"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such alert of this tenant (another tenant's, or a platform alert for anyone but a platform admin, answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/seq-gaps": {
      "get": {
        "operationId": "listSeqGaps",
        "summary": "Open sequence gaps of the tenant's devices",
        "description": "B9 (#21): the ranges of sequence numbers the tenant's devices have not sent yet, ascending by device and first missing number, one page (`limit`, default 50, at most 200; `cursor` from the previous page). A gap leaves the list when its messages arrive. Allowed for tenant_admin, auditor and platform_admin acting for the tenant, and an operator within its facilities (a device's facility, or its site when it has none). Not audited (a read). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "ops"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_read"
            ]
          }
        ],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device_id",
            "in": "query",
            "required": false,
            "description": "Only the gaps of this device.",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128
            },
            "example": "scale-1"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size: 1 to 200 gaps (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6WyJzY2FsZS0xIiw0XX0"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of open gaps.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SeqGapPage"
                },
                "example": {
                  "items": [
                    {
                      "device_id": "scale-1",
                      "start_seq": 4,
                      "end_seq": 6,
                      "missing": 3,
                      "opened_at": 1790000000.5,
                      "alerted": true
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `device_id`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "device_id": {
                    "value": {
                      "error": "bad device_id",
                      "code": "bad_device_id"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, auditor, platform_admin and an operator through a signed-in session or an operator API client) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/outbound": {
      "get": {
        "operationId": "getOutboundBacklog",
        "summary": "Outbound delivery backlog of the tenant",
        "description": "B9 (#21): the tenant's events not yet delivered to each outbound target (national system, a buyer's EPCIS repository, an archive), with a tenant-neutral summary of the error of the event that failed most often (the full text for platform_admin only). Every configured target is listed, with zeros when nothing waits. Allowed for tenant_admin, auditor and platform_admin acting for the tenant. Not audited (a read). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "ops"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The backlog per target.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OutboundBacklog"
                },
                "example": {
                  "targets": [
                    {
                      "target": "epcis",
                      "pending": 12,
                      "held": 1,
                      "failing": 12,
                      "next_attempt_at": 1790000960.5,
                      "max_attempts": 5,
                      "last_error": "HTTP 503"
                    },
                    {
                      "target": "file",
                      "pending": 0,
                      "held": 0,
                      "failing": 0,
                      "next_attempt_at": null,
                      "max_attempts": 0,
                      "last_error": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, auditor and platform_admin) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/rejections": {
      "get": {
        "operationId": "listRejections",
        "summary": "Refused device messages",
        "description": "B9 (#21): the device messages the server refused, newest first, one page (`limit`, default 50, at most 200; `cursor` from the previous page), never their payload (its size only). The record has no tenant (a refused message cannot be trusted to come from the tenant its route names), so the list is for platform_admin only, every tenant's; any other role is refused 403. Not audited (a read). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "ops"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "reason",
            "in": "query",
            "required": false,
            "description": "Only messages refused for this reason.",
            "schema": {
              "type": "string",
              "pattern": "^[a-z0-9_]{1,64}$"
            },
            "example": "bad_signature"
          },
          {
            "name": "tenant",
            "in": "query",
            "required": false,
            "description": "Only messages whose route names this tenant (its first segment).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128
            },
            "example": "coop-dl"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size: 1 to 200 messages (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjQxfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of refused messages.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RejectionPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 41,
                      "route": "coop-dl/ph1/scale-1/event/ObjectEvent",
                      "envelope_id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                      "reason": "bad_signature",
                      "received_at": 1790000000.5,
                      "payload_bytes": 812
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `reason`, `tenant`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "reason": {
                    "value": {
                      "error": "bad reason",
                      "code": "bad_reason"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "bad tenant",
                      "code": "bad_tenant"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/attachments/{sha256}": {
      "get": {
        "operationId": "getAttachment",
        "summary": "Download a blob",
        "description": "Admins and auditors tenant-wide; an operator through envelopes of its facilities, and a tenant-owned upload (it has no facility) only when a certification, spray record or satellite check of a growing area of its tenant (or an unowned one) cites it. Visible when an envelope of the caller's tenant references the hash and its bytes were uploaded for that reference, or the caller's tenant uploaded it. The Content-Type is the stored media type. Not public: no /v1/public/ route serves blobs. The photo of a land-use right certificate (#250: a hash that a land certificate of a growing area of the caller's company names as its `photo_sha256`) holds the land user's personal data: it is served only to a caller that may read land certificates (the company's tenant admins and a platform admin acting for it) through a signed-in session, never to an auditor, an operator, an API token or an OAuth client, which get 404.",
        "x-sdk-description": "Admins and auditors tenant-wide; an operator through envelopes of its facilities, and a tenant-owned upload (it has no facility) only when a certification, spray record or satellite check of a growing area of its tenant (or an unowned one) cites it. Visible when an envelope of the caller's tenant references the hash and its bytes were uploaded for that reference, or the caller's tenant uploaded it. The Content-Type is the stored media type. Not public: no /v1/public/ route serves blobs.",
        "tags": [
          "attachments"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "attachment_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "sha256",
            "in": "path",
            "required": true,
            "description": "SHA-256 of the blob: exactly 64 lowercase hex characters (anything else is 400 before any lookup).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
          }
        ],
        "responses": {
          "200": {
            "description": "The blob's bytes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Content-Type-Options": {
                "description": "Always `nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "Always `attachment; filename=\"<sha256>.<wav|jpg|png|pdf>\"`: never rendered in the app origin.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Security-Policy": {
                "description": "Always `default-src 'none'; sandbox`.",
                "schema": {
                  "type": "string"
                }
              },
              "Cache-Control": {
                "description": "`private, no-cache`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/pdf": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "application/pdf"
                },
                "example": "%PDF-1.7 ... (binary PDF bytes)"
              },
              "audio/wav": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "audio/wav"
                },
                "example": "RIFF....WAVEfmt  ... (binary PCM WAV bytes)"
              },
              "image/jpeg": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "image/jpeg"
                },
                "example": "(binary JPEG bytes, starting FF D8 FF)"
              },
              "image/png": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "image/png"
                },
                "example": "(binary PNG bytes, starting 89 50 4E 47 0D 0A 1A 0A)"
              }
            }
          },
          "400": {
            "description": "Malformed sha256 in the path, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_hash": {
                    "value": {
                      "error": "invalid hash",
                      "code": "invalid_hash"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No blob this caller may see: never uploaded, referenced but not uploaded yet, owned by another tenant, or (for a facility-scoped operator) referenced only by envelopes outside its facilities or a tenant upload no growing-area record cites, all answer exactly alike. So does a land certificate's photo for a caller that may not read land certificates through a signed-in session.",
            "x-sdk-description": "No blob this caller may see: never uploaded, referenced but not uploaded yet, owned by another tenant, or (for a facility-scoped operator) referenced only by envelopes outside its facilities or a tenant upload no growing-area record cites, all answer exactly alike.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "uploadAttachment",
        "summary": "Upload a blob owned by the caller's tenant",
        "description": "For blobs no envelope references (a satellite-check image, a lab PDF). platform_admin and tenant_admin; the owner is the tenant the caller acts for (X-Tenant for a platform admin). The body must hash to `sha256`, be at most 1 MiB, have an allowlisted Content-Type (parameters ignored) and that type's signature. A blob the tenant already owns: 200 without reading the body. Audited (`attachment.upload`: the hash, media type and size, never the bytes).",
        "tags": [
          "attachments"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "attachment_upload"
            ]
          }
        ],
        "parameters": [
          {
            "name": "sha256",
            "in": "path",
            "required": true,
            "description": "SHA-256 of the blob: exactly 64 lowercase hex characters (anything else is 400 before any lookup).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/pdf": {
              "schema": {
                "type": "string",
                "contentMediaType": "application/pdf"
              },
              "example": "%PDF-1.7 ... (binary PDF bytes)"
            },
            "audio/wav": {
              "schema": {
                "type": "string",
                "contentMediaType": "audio/wav"
              },
              "example": "RIFF....WAVEfmt  ... (binary PCM WAV bytes)"
            },
            "image/jpeg": {
              "schema": {
                "type": "string",
                "contentMediaType": "image/jpeg"
              },
              "example": "(binary JPEG bytes, starting FF D8 FF)"
            },
            "image/png": {
              "schema": {
                "type": "string",
                "contentMediaType": "image/png"
              },
              "example": "(binary PNG bytes, starting 89 50 4E 47 0D 0A 1A 0A)"
            }
          }
        },
        "responses": {
          "200": {
            "description": "The tenant already owns this blob; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AttachmentStored"
                },
                "example": {
                  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "media_type": "audio/wav",
                  "size": 115244
                }
              }
            }
          },
          "201": {
            "description": "Stored and owned by the caller's tenant.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AttachmentStored"
                },
                "example": {
                  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "media_type": "audio/wav",
                  "size": 115244
                }
              }
            }
          },
          "400": {
            "description": "Malformed sha256 in the path, a missing or malformed Content-Length, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_hash": {
                    "value": {
                      "error": "invalid hash",
                      "code": "invalid_hash"
                    }
                  },
                  "bad_content_length": {
                    "value": {
                      "error": "bad content length",
                      "code": "bad_content_length"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin_not_allowed": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "415": {
            "description": "Media type outside the allowlist (audio/wav, image/jpeg, image/png, application/pdf) or not the one declared, or bytes that do not start with that type's signature.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unsupported_media_type": {
                    "value": {
                      "error": "unsupported media type",
                      "code": "unsupported_media_type"
                    }
                  },
                  "content_does_not_match_the_media_type": {
                    "value": {
                      "error": "content does not match the media type",
                      "code": "content_does_not_match_the_media_type"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "The body does not hash to `sha256`; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "hash mismatch",
                  "code": "hash_mismatch"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/attachments/{sha256}/peaks": {
      "get": {
        "operationId": "getAttachmentPeaks",
        "summary": "Waveform peaks of a WAV blob",
        "description": "Same visibility as the blob. PCM 8/16/24/32-bit WAV, any channel count. The frames are split into `n` buckets as evenly as integer division allows (one bucket per frame when there are fewer frames than `n`); each bucket is `[min, max]` over every sample of every channel, normalised to -1..1 of full scale and rounded to 4 decimals.",
        "tags": [
          "attachments"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "attachment_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "sha256",
            "in": "path",
            "required": true,
            "description": "SHA-256 of the blob: exactly 64 lowercase hex characters (anything else is 400 before any lookup).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
          },
          {
            "name": "n",
            "in": "query",
            "required": false,
            "description": "Number of buckets, 1 to 4096 (default 560).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 4096,
              "default": 560
            },
            "example": 560
          }
        ],
        "responses": {
          "200": {
            "description": "The peaks.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`private, no-cache`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AttachmentPeaks"
                },
                "example": {
                  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "n": 4,
                  "channels": 1,
                  "sample_rate": 48000,
                  "frames": 57600,
                  "duration_s": 1.2,
                  "peaks": [
                    [
                      -0.5,
                      0.5
                    ],
                    [
                      -0.25,
                      0.75
                    ],
                    [
                      0.0,
                      0.0
                    ],
                    [
                      -1.0,
                      0.9999
                    ]
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Malformed sha256 in the path, `n` not an integer from 1 to 4096, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_hash": {
                    "value": {
                      "error": "invalid hash",
                      "code": "invalid_hash"
                    }
                  },
                  "bad_n": {
                    "value": {
                      "error": "bad n",
                      "code": "bad_n"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No blob this caller may see: never uploaded, referenced but not uploaded yet, owned by another tenant, or (for a facility-scoped operator) referenced only by envelopes outside its facilities or a tenant upload no growing-area record cites, all answer exactly alike.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "415": {
            "description": "The blob is not audio/wav, or not a PCM WAV the server can read.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_a_wav_attachment": {
                    "value": {
                      "error": "not a wav attachment",
                      "code": "not_a_wav_attachment"
                    }
                  },
                  "not_a_pcm_wav_attachment": {
                    "value": {
                      "error": "not a pcm wav attachment",
                      "code": "not_a_pcm_wav_attachment"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/company/profile": {
      "get": {
        "operationId": "getCompanyProfile",
        "summary": "Read the selected company's profile",
        "description": "SELF-1-5 (#186). The legal name, address, tax or registration number, contact person, website and logo of the company the caller acts for (X-Tenant). Admins, auditors and operators (operators print labels), tenant-wide; a lab is refused. Not available to API clients (OAuth2): company account management. A company that never saved a profile answers its display name and empty fields.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "responses": {
          "200": {
            "description": "The company's profile.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyProfile"
                },
                "example": {
                  "tenant": "coop-dl",
                  "name": "Coop DL",
                  "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
                  "trading_name": "Durian DL",
                  "address": "12 Nguyễn Tất Thành",
                  "province": "Đắk Lắk",
                  "district": "Buôn Ma Thuột",
                  "country": "VN",
                  "tax_id": "6001234567",
                  "contact_name": "Nguyễn Văn A",
                  "contact_phone": "+84 912 345 678",
                  "contact_email": "a.nguyen@coop.example",
                  "website": "https://coop.example",
                  "logo": {
                    "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                    "media_type": "image/png",
                    "size": 20480
                  },
                  "updated_at": 1791000000.0,
                  "updated_by": "admin@coop.example"
                }
              }
            }
          },
          "400": {
            "description": "`admin_units` is not 0 or 1, or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_admin_units": {
                    "value": {
                      "error": "bad admin_units",
                      "code": "bad_admin_units"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "$ref": "#/components/responses/BadRequestId"
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named a company (X-Tenant) that does not exist. A member names only its own companies (any other is 403 tenant not allowed), so another company's profile is never reached.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "parameters": [
          {
            "name": "admin_units",
            "in": "query",
            "required": false,
            "description": "#273: `1` adds the address by official code (`province_code`, `commune_code`, `admin_units_version`, `address_status`, `address_before_reform`, `address_candidates`, `commune`); `0` or none leaves them out and answers exactly as before; any other value is refused (400 `bad admin_units`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ]
      },
      "put": {
        "operationId": "putCompanyProfile",
        "summary": "Save the selected company's profile",
        "description": "SELF-1-5 (#186). Company admins; a platform admin edits any company through X-Tenant. Replaces the whole profile (the logo is kept). `tenants.name` stays the short display name. Audited (`company.profile.update`): the prior profile's hash and the NAMES of the fields that changed, never a value (contact details are personal data). Lots already sealed keep the details they were sealed with. #273: the address in Viet Nam is given by official code, `province_code` and `commune_code` from `getAdminUnits`; the server writes the official names (`district` null). The text fields `province` and `district` of a profile in Viet Nam are deprecated (sunset 1 May 2027): a text-only address is still accepted, stores the record as not yet coded and answers with the `Deprecation`, `Sunset` and `Link` headers. In another country the codes are refused and the text stays the region and locality, not deprecated.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CompanyProfileUpdate"
              },
              "example": {
                "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
                "trading_name": "Durian DL",
                "address": "12 Nguyễn Tất Thành",
                "province_code": "66",
                "commune_code": "24133",
                "country": "VN",
                "tax_id": "6001234567",
                "contact_name": "Nguyễn Văn A",
                "contact_phone": "+84 912 345 678",
                "contact_email": "a.nguyen@coop.example",
                "website": "https://coop.example"
              },
              "x-sdk-example": {
                "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
                "trading_name": "Durian DL",
                "address": "12 Nguyễn Tất Thành",
                "province": "Đắk Lắk",
                "district": "Buôn Ma Thuột",
                "country": "VN",
                "tax_id": "6001234567",
                "contact_name": "Nguyễn Văn A",
                "contact_phone": "+84 912 345 678",
                "contact_email": "a.nguyen@coop.example",
                "website": "https://coop.example"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Saved; the profile as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Deprecation": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`; for a company profile, `country` VN or absent), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `@1792195200` (RFC 9745): the text-only address was deprecated at the start of 17 October 2026, UTC.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Sunset": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`; for a company profile, `country` VN or absent), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `Sat, 01 May 2027 00:00:00 GMT` (RFC 8594): from then a text-only address in Viet Nam may be refused.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Link": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`; for a company profile, `country` VN or absent), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `<https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"deprecation\", <https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"sunset\"`: the changelog entry that says what to send instead.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyProfile"
                },
                "example": {
                  "tenant": "coop-dl",
                  "name": "Coop DL",
                  "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
                  "trading_name": "Durian DL",
                  "address": "12 Nguyễn Tất Thành",
                  "province": "Tỉnh Đắk Lắk",
                  "district": null,
                  "country": "VN",
                  "tax_id": "6001234567",
                  "contact_name": "Nguyễn Văn A",
                  "contact_phone": "+84 912 345 678",
                  "contact_email": "a.nguyen@coop.example",
                  "website": "https://coop.example",
                  "logo": {
                    "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                    "media_type": "image/png",
                    "size": 20480
                  },
                  "updated_at": 1791000000.0,
                  "updated_by": "admin@coop.example"
                },
                "x-sdk-example": {
                  "tenant": "coop-dl",
                  "name": "Coop DL",
                  "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
                  "trading_name": "Durian DL",
                  "address": "12 Nguyễn Tất Thành",
                  "province": "Đắk Lắk",
                  "district": "Buôn Ma Thuột",
                  "country": "VN",
                  "tax_id": "6001234567",
                  "contact_name": "Nguyễn Văn A",
                  "contact_phone": "+84 912 345 678",
                  "contact_email": "a.nguyen@coop.example",
                  "website": "https://coop.example",
                  "logo": {
                    "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                    "media_type": "image/png",
                    "size": 20480
                  },
                  "updated_at": 1791000000.0,
                  "updated_by": "admin@coop.example"
                }
              }
            }
          },
          "400": {
            "description": "A field outside its rules (the code names the field), an unknown field, a body that is not a JSON object, or a bad X-Request-Id. #273: also a code that is not in the administrative units list in force (`admin_unit_unknown`), a commune that the list places in another province (`commune_not_in_province`), a district (`district_with_codes`) or a province name sent with the codes (`invalid_province`), or a malformed code or one code without the other (`invalid_province_code`, `invalid_commune_code`), or codes for a profile in another country (`invalid_country`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_legal_name": {
                    "value": {
                      "error": "invalid legal_name: required, a string of 1 to 200 characters",
                      "code": "invalid_legal_name"
                    }
                  },
                  "invalid_country": {
                    "value": {
                      "error": "invalid country: an ISO 3166-1 alpha-2 code in capital letters, such as VN",
                      "code": "invalid_country"
                    }
                  },
                  "invalid_website": {
                    "value": {
                      "error": "invalid website: an https:// address such as https://example.com",
                      "code": "invalid_website"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: tenant",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "admin_unit_unknown": {
                    "value": {
                      "error": "admin unit unknown: commune 99999 is not in the official list vn-2026-10-17",
                      "code": "admin_unit_unknown"
                    }
                  },
                  "commune_not_in_province": {
                    "value": {
                      "error": "commune not in province: commune 00004 (Phường Ba Đình) is in province 01 (Thành phố Hà Nội), not in 82 (Tỉnh Đồng Tháp)",
                      "code": "commune_not_in_province"
                    }
                  },
                  "district_with_codes": {
                    "value": {
                      "error": "district with codes: Viet Nam has no district level since 2025-07-01; send it null",
                      "code": "district_with_codes"
                    }
                  },
                  "invalid_province": {
                    "value": {
                      "error": "invalid province: absent or null with the codes, the server writes the official name",
                      "code": "invalid_province"
                    }
                  },
                  "invalid_province_code": {
                    "value": {
                      "error": "invalid province_code: the official code, 2 digits as a string, sent with commune_code",
                      "code": "invalid_province_code"
                    }
                  },
                  "invalid_commune_code": {
                    "value": {
                      "error": "invalid commune_code: the official code, 5 digits as a string, sent with province_code",
                      "code": "invalid_commune_code"
                    }
                  },
                  "codes_outside_vietnam": {
                    "value": {
                      "error": "invalid country: province_code and commune_code apply to an address in Viet Nam (VN)",
                      "code": "invalid_country"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "A field outside its rules (the code names the field), an unknown field, a body that is not a JSON object, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "invalid_legal_name": {
                      "value": {
                        "error": "invalid legal_name: required, a string of 1 to 200 characters",
                        "code": "invalid_legal_name"
                      }
                    },
                    "invalid_country": {
                      "value": {
                        "error": "invalid country: an ISO 3166-1 alpha-2 code in capital letters, such as VN",
                        "code": "invalid_country"
                      }
                    },
                    "invalid_website": {
                      "value": {
                        "error": "invalid website: an https:// address such as https://example.com",
                        "code": "invalid_website"
                      }
                    },
                    "unknown_field": {
                      "value": {
                        "error": "unknown field: tenant",
                        "code": "unknown_field"
                      }
                    },
                    "invalid_json": {
                      "value": {
                        "error": "invalid JSON",
                        "code": "invalid_json"
                      }
                    },
                    "bad_request_id": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin_not_allowed": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named a company (X-Tenant) that does not exist. A member names only its own companies (any other is 403 tenant not allowed), so another company's profile is never reached.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "503": {
            "description": "#273: `province_code` and `commune_code` were sent but the server has no administrative units list in force to check them (`administrative_units_catalog_unavailable`); nothing was written. A text-only address is not refused this way.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "administrative units catalog unavailable",
                  "code": "administrative_units_catalog_unavailable"
                }
              }
            },
            "x-not-in-sdk": true
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "SELF-1-5 (#186). Company admins; a platform admin edits any company through X-Tenant. Replaces the whole profile (the logo is kept). `tenants.name` stays the short display name. Audited (`company.profile.update`): the prior profile's hash and the NAMES of the fields that changed, never a value (contact details are personal data). Lots already sealed keep the details they were sealed with."
      }
    },
    "/v1/company/profile/public-identity": {
      "get": {
        "operationId": "getCompanyPublicIdentity",
        "summary": "Read how the selected company is named on public outputs",
        "description": "#208. Whether the company the caller acts for (X-Tenant) is a household business (hộ kinh doanh), its two opt-ins, and `public_producer`: the producer exactly as the lot's public customs file shows it now. For a company: its legal name and full address. For a household business, whose legal name is a person's name and whose address is often a home: its trading name (or 'Hộ kinh doanh' alone when it has none, never its tax number) and its province only, unless it opted in. Labels, the company's own export and the profile keep the legal name and full address. Readers as for the profile. Kept apart from the profile so the profile's body stays what SDK 0.2.0 decodes. A company that never saved a profile answers false for every flag and a null `public_producer`. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The company's public identity.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyPublicIdentity"
                },
                "example": {
                  "household_business": true,
                  "public_full_address": false,
                  "public_legal_name": false,
                  "public_producer": {
                    "legal_name": "Sầu riêng Bảy Tân Phú",
                    "address": null,
                    "district": null,
                    "province": "Tiền Giang",
                    "country": "VN"
                  }
                }
              }
            }
          },
          "400": {
            "description": "`admin_units` is not 0 or 1, or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_admin_units": {
                    "value": {
                      "error": "bad admin_units",
                      "code": "bad_admin_units"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named a company (X-Tenant) that does not exist. A member names only its own companies (any other is 403 tenant not allowed), so another company's public identity is never reached.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "parameters": [
          {
            "name": "admin_units",
            "in": "query",
            "required": false,
            "description": "#273: `1` adds `public_producer.commune`, the company's commune (official name; null for a household business that has not opted in to its full address); `0` or none leaves it out and answers exactly as before; any other value is refused (400 `bad admin_units`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ]
      },
      "put": {
        "operationId": "putCompanyPublicIdentity",
        "summary": "Set how the selected company is named on public outputs",
        "description": "#208. Company admins; a platform admin through X-Tenant. Sets whether the company is a household business and its two opt-ins; every flag is required. The opt-ins apply to a household business only and are stored false for a company. The profile's fields are not changed, and saving the profile never changes these flags. The profile must be saved first. Audited (`company.public_identity.update`): the prior profile's hash and the NAMES of the flags that changed, never a value. Lots already sealed are not changed; the public customs file reads the profile when it is opened, so it shows the change after the edge cache (at most 60 s). Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CompanyPublicIdentityUpdate"
              },
              "example": {
                "household_business": true,
                "public_full_address": false,
                "public_legal_name": false
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Saved; the public identity as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyPublicIdentity"
                },
                "example": {
                  "household_business": true,
                  "public_full_address": false,
                  "public_legal_name": false,
                  "public_producer": {
                    "legal_name": "Sầu riêng Bảy Tân Phú",
                    "address": null,
                    "district": null,
                    "province": "Tiền Giang",
                    "country": "VN"
                  }
                }
              }
            }
          },
          "400": {
            "description": "A flag that is missing or not true or false (the code names it), an unknown field, a body that is not a JSON object, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_household_business": {
                    "value": {
                      "error": "invalid household_business: required, true or false",
                      "code": "invalid_household_business"
                    }
                  },
                  "invalid_public_full_address": {
                    "value": {
                      "error": "invalid public_full_address: required, true or false",
                      "code": "invalid_public_full_address"
                    }
                  },
                  "invalid_public_legal_name": {
                    "value": {
                      "error": "invalid public_legal_name: required, true or false",
                      "code": "invalid_public_legal_name"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: legal_name",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin_not_allowed": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named a company (X-Tenant) that does not exist. A member names only its own companies (any other is 403 tenant not allowed), so another company's public identity is never reached.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The company has not saved its profile yet: save the profile first.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "no company profile: save the company profile before its public identity",
                  "code": "no_company_profile"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/company/security": {
      "get": {
        "operationId": "getCompanySecurity",
        "summary": "Read the company's sign-in security",
        "description": "SELF-1-6 (#187). Whether the selected company (X-Tenant) requires two-step sign-in, how many active members have it on, and the date from which company admins must use it. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The company's sign-in security.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanySecurity"
                },
                "example": {
                  "require_two_factor": true,
                  "members": 12,
                  "members_with_two_factor": 9,
                  "admin_deadline": 1795270400.0,
                  "updated_at": 1790086400.5,
                  "updated_by": "admin@coop.example"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "updateCompanySecurity",
        "summary": "Require two-step sign-in for the company, or stop",
        "description": "SELF-1-6 (#187). When `require_two_factor` is on, a member of this company whose session has not proved a second factor can call only the session routes (/v1/auth/*) and gets 403 `two_factor_required` on every route of this company, until they set up the app. Turning it on needs the caller's own two-step sign-in (409 otherwise). Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`company.security.update`, in the same transaction). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403). Second admin approval (INTEGRITY-3, #203): while the company requires a second admin (PUT /v1/company/four-eyes), a direct call answers 403 `second_admin_approval_required` before anything is done (no audit row, no Idempotency-Key used): ask for it with POST /v1/approval-requests, and another admin of the company approves it.",
        "x-sdk-description": "SELF-1-6 (#187). When `require_two_factor` is on, a member of this company whose session has not proved a second factor can call only the session routes (/v1/auth/*) and gets 403 `two_factor_required` on every route of this company, until they set up the app. Turning it on needs the caller's own two-step sign-in (409 otherwise). Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`company.security.update`, in the same transaction). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CompanySecurityUpdate"
              },
              "example": {
                "require_two_factor": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The company's sign-in security.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanySecurity"
                },
                "example": {
                  "require_two_factor": true,
                  "members": 12,
                  "members_with_two_factor": 9,
                  "admin_deadline": 1795270400.0,
                  "updated_at": 1790086400.5,
                  "updated_by": "admin@coop.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, or `require_two_factor` missing or not true or false; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "missing": {
                    "value": {
                      "error": "require_two_factor is required",
                      "code": "require_two_factor_is_required"
                    }
                  },
                  "type": {
                    "value": {
                      "error": "require_two_factor must be true or false",
                      "code": "require_two_factor_must_be_true_or_false"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Turning it on while the caller's own two-step sign-in is off.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "set up two-step sign-in for yourself first",
                  "code": "set_up_two_step_sign_in_for_yourself_first"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/company/onboarding": {
      "get": {
        "operationId": "getCompanyOnboarding",
        "summary": "Read the company's getting-started checklist",
        "description": "SELF-1-8 (#189). The steps that take the selected company (X-Tenant) from an empty workspace to its first labelled lot, in order, each `done`, `to_do` or `waiting_for_platform`, computed from the company's own records (counts only; another company's records never count). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The company's checklist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Onboarding"
                },
                "example": {
                  "tenant": "coop-dl",
                  "complete": false,
                  "hidden": false,
                  "hidden_at": null,
                  "steps": [
                    {
                      "id": "profile",
                      "required": true,
                      "status": "done",
                      "count": 3,
                      "total": 3,
                      "link": "/admin/settings#profile"
                    },
                    {
                      "id": "second_admin",
                      "required": true,
                      "status": "to_do",
                      "count": 1,
                      "total": null,
                      "link": "/admin/settings#team"
                    },
                    {
                      "id": "admin_two_factor",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": 1,
                      "link": "/admin/settings#security"
                    },
                    {
                      "id": "facility",
                      "required": true,
                      "status": "waiting_for_platform",
                      "count": 0,
                      "total": 1,
                      "link": "/admin/facilities"
                    },
                    {
                      "id": "growing_areas",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": 0,
                      "link": "/admin/growing-areas"
                    },
                    {
                      "id": "operators",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/admin/settings#team"
                    },
                    {
                      "id": "issuer_keys",
                      "required": true,
                      "status": "waiting_for_platform",
                      "count": 0,
                      "total": 0,
                      "link": "/admin/settings/issuer-keys"
                    },
                    {
                      "id": "devices",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": 0,
                      "link": "/admin/devices"
                    },
                    {
                      "id": "first_lot",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/console/lots/new"
                    },
                    {
                      "id": "first_sealed_lot",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/console"
                    },
                    {
                      "id": "first_label",
                      "required": true,
                      "status": "to_do",
                      "count": null,
                      "total": null,
                      "link": "/console"
                    },
                    {
                      "id": "integrations",
                      "required": false,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/admin/settings/api-tokens"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused; operators and auditors are refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "updateCompanyOnboarding",
        "summary": "Hide the company's getting-started checklist, or show it again",
        "description": "SELF-1-8 (#189). `hidden` true hides the checklist for every admin of the selected company (X-Tenant); false shows it again. Hiding an already hidden checklist keeps the first time. The only thing the checklist stores. Audited (`company.onboarding.update`, in the same transaction). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OnboardingUpdate"
              },
              "example": {
                "hidden": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The company's checklist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Onboarding"
                },
                "example": {
                  "tenant": "coop-dl",
                  "complete": false,
                  "hidden": true,
                  "hidden_at": 1790086400.5,
                  "steps": [
                    {
                      "id": "profile",
                      "required": true,
                      "status": "done",
                      "count": 3,
                      "total": 3,
                      "link": "/admin/settings#profile"
                    },
                    {
                      "id": "second_admin",
                      "required": true,
                      "status": "to_do",
                      "count": 1,
                      "total": null,
                      "link": "/admin/settings#team"
                    },
                    {
                      "id": "admin_two_factor",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": 1,
                      "link": "/admin/settings#security"
                    },
                    {
                      "id": "facility",
                      "required": true,
                      "status": "waiting_for_platform",
                      "count": 0,
                      "total": 1,
                      "link": "/admin/facilities"
                    },
                    {
                      "id": "growing_areas",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": 0,
                      "link": "/admin/growing-areas"
                    },
                    {
                      "id": "operators",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/admin/settings#team"
                    },
                    {
                      "id": "issuer_keys",
                      "required": true,
                      "status": "waiting_for_platform",
                      "count": 0,
                      "total": 0,
                      "link": "/admin/settings/issuer-keys"
                    },
                    {
                      "id": "devices",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": 0,
                      "link": "/admin/devices"
                    },
                    {
                      "id": "first_lot",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/console/lots/new"
                    },
                    {
                      "id": "first_sealed_lot",
                      "required": true,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/console"
                    },
                    {
                      "id": "first_label",
                      "required": true,
                      "status": "to_do",
                      "count": null,
                      "total": null,
                      "link": "/console"
                    },
                    {
                      "id": "integrations",
                      "required": false,
                      "status": "to_do",
                      "count": 0,
                      "total": null,
                      "link": "/admin/settings/api-tokens"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, or `hidden` missing or not true or false; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "hidden": {
                    "value": {
                      "error": "hidden must be true or false",
                      "code": "hidden_must_be_true_or_false"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused; operators and auditors are refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/company/exports": {
      "get": {
        "operationId": "listCompanyExports",
        "summary": "List the company's full data exports",
        "description": "SELF-2-3 (#192). The selected company's (X-Tenant) 20 newest export requests, newest first, with their state, and how many may be requested a day. Never another company's. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The company's export requests.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyExportList"
                },
                "example": {
                  "items": [
                    {
                      "id": 13,
                      "status": "queued",
                      "requested_by": "admin@coop.example",
                      "requested_at": 1790090000.0,
                      "started_at": null,
                      "finished_at": null,
                      "expires_at": null,
                      "size": null,
                      "sha256": null,
                      "file_name": null,
                      "error": null
                    },
                    {
                      "id": 12,
                      "status": "ready",
                      "requested_by": "admin@coop.example",
                      "requested_at": 1790000000.5,
                      "started_at": 1790000030.0,
                      "finished_at": 1790000041.25,
                      "expires_at": 1790086441.25,
                      "size": 1843211,
                      "sha256": "9f2c4a7d1e0b6c3f8a5d2e7b4c1f9a6d3e0b7c4f1a8d5e2b9c6f3a0d7e4b1c8f",
                      "file_name": "croppath-export-coop-dl-20260921T143320Z.zip",
                      "error": null
                    }
                  ],
                  "max_per_day": 3,
                  "download_hours": 24
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), or two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "requestCompanyExport",
        "summary": "Request a full data export of the company",
        "description": "SELF-2-3 (#192). Queues a dated archive (ZIP of CSV and JSON files) of everything the selected company (X-Tenant) holds: profile, facilities, growing areas, growers, devices, lots, device events, cartons, shipments, lab reports and results, members (never a password, two-step secret, backup code, token, webhook secret or private key) and the activity log. A background job builds it within minutes; GET /v1/company/exports shows when it is ready, and it can be downloaded for 24 hours. One export per company at a time (409 `export_in_progress`) and at most 3 requests in any 24 hours (429 `too_many_exports`, with Retry-After). Send no body (or `{}`). Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`export.company.request`, in the same transaction). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "202": {
            "description": "The export is queued.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyExport"
                },
                "example": {
                  "id": 13,
                  "status": "queued",
                  "requested_by": "admin@coop.example",
                  "requested_at": 1790090000.0,
                  "started_at": null,
                  "finished_at": null,
                  "expires_at": null,
                  "size": null,
                  "sha256": null,
                  "file_name": null,
                  "error": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body with any field, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: format",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required, origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "An export of the company is already waiting or being built. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "export_in_progress": {
                    "value": {
                      "error": "export in progress: an export of the company is already being prepared",
                      "code": "export_in_progress"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "429": {
            "description": "The company already requested 3 exports in the last 24 hours; `Retry-After` says when the next one may be requested.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many exports: at most 3 in 24 hours",
                  "code": "too_many_exports"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/company/exports/{id}/download": {
      "get": {
        "operationId": "downloadCompanyExport",
        "summary": "Download a ready full data export",
        "description": "SELF-2-3 (#192). The archive of the selected company's (X-Tenant) export `id` as `application/zip`, streamed from the stored file, for 24 hours after it was ready. Another company's export answers 404 like one that does not exist. The archive layout (files, columns, encoding, times) is documented at /developers/downloads/company-export.md. Needs a password confirmed within the last 10 minutes (SELF-1-2). An audited read (`export.company`: the archive's size and SHA-256); never cached. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The export's id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          }
        ],
        "responses": {
          "200": {
            "description": "The ZIP archive.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"<file_name>\"`, the export's `file_name`.",
                "schema": {
                  "type": "string"
                }
              },
              "Cache-Control": {
                "description": "`private, no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/zip": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "application/zip"
                },
                "example": "(binary ZIP bytes, starting 50 4B 03 04)"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), or two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such export of the selected company (another company's export answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The export is still being prepared, or its build failed (request a new one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_ready": {
                    "value": {
                      "error": "export not ready: it is still being prepared",
                      "code": "export_not_ready"
                    }
                  },
                  "failed": {
                    "value": {
                      "error": "export failed: request a new one",
                      "code": "export_failed"
                    }
                  }
                }
              }
            }
          },
          "410": {
            "description": "The export's 24 hours are over and its file is deleted: request a new one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "export expired: request a new one",
                  "code": "export_expired"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/notifications": {
      "get": {
        "operationId": "listNotifications",
        "summary": "List the caller's notifications",
        "description": "SELF-2-6 (#195). The caller's own in-app notifications in the selected company (X-Tenant), newest first, one page, with the number still unread. Each is a `kind` and its `params` (identifiers, names and times, never rendered text): the console words it in the reader's language. Company admins receive them (and a platform admin who invited a company's first admin, under that company): an invitation accepted or expiring within a day, a webhook turned off after repeated failures, an API token expiring within 14 days, a facility approved or refused, a growing area approved, a public mismatch report (at most one per lot and day), a facility with lots still open and no signing key. There is no email. Read notifications are deleted 90 days after they were created. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "unread",
            "in": "query",
            "required": false,
            "description": "`true`: only the unread ones (default `false`).",
            "schema": {
              "type": "string",
              "enum": [
                "true",
                "false"
              ]
            },
            "example": "true"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 100 (default 20).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100
            },
            "example": 20
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjQxfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the caller's notifications (`Cache-Control: no-store`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NotificationPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 41,
                      "kind": "api_token_expiring",
                      "params": {
                        "token_id": 7,
                        "name": "erp-sync",
                        "expires_at": 1797776000.5
                      },
                      "created_at": 1797000000.5,
                      "read_at": null
                    }
                  ],
                  "unread": 1,
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `unread`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "unread": {
                    "value": {
                      "error": "unread must be true or false",
                      "code": "unread_must_be_true_or_false"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/notifications/unread-count": {
      "get": {
        "operationId": "getNotificationUnreadCount",
        "summary": "Count the caller's unread notifications",
        "description": "SELF-2-6 (#195). How many of the caller's notifications in the selected company are unread: the bell's badge in the console's top bar. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The unread count (`Cache-Control: no-store`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NotificationUnreadCount"
                },
                "example": {
                  "unread": 3
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/notifications/read-all": {
      "post": {
        "operationId": "markAllNotificationsRead",
        "summary": "Mark all of the caller's notifications read",
        "description": "SELF-2-6 (#195). Marks every unread notification of the caller in the selected company read; another user's and another company's stay as they are. Not audited: it changes only the reader's own view of their list (each notification records when it was read). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "How many were marked read, and how many are unread now.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NotificationsMarkedRead"
                },
                "example": {
                  "marked": 3,
                  "unread": 0
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/notifications/{id}/read": {
      "post": {
        "operationId": "markNotificationRead",
        "summary": "Mark one of the caller's notifications read",
        "description": "SELF-2-6 (#195). Marks the notification read (a read one keeps its first `read_at`). Another user's notification, or one of another company, answers 404 like a missing one. Not audited: it changes only the reader's own view of their list. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The notification id (from listNotifications).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "41"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The notification, read.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Notification"
                },
                "example": {
                  "id": 41,
                  "kind": "api_token_expiring",
                  "params": {
                    "token_id": 7,
                    "name": "erp-sync",
                    "expires_at": 1797776000.5
                  },
                  "created_at": 1797000000.5,
                  "read_at": 1797000600.5
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No notification of the caller in this company with this id (another user's, another company's, purged or never created).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 41",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/company/usage": {
      "get": {
        "operationId": "getCompanyUsage",
        "summary": "Read the company's usage and limits",
        "description": "SELF-2-5 (#194). For the selected company (X-Tenant): how much of each per-company limit it uses, counted by the same query the limit checks before a create, against the limit the backend enforces, and its API calls on each of the last 14 UTC days. Counts only; another company's records never count. An entry warns from `warn_percent` of its limit and is `reached` at the limit (the next create is refused). An API call is a request authenticated by an API token or an API client's access token of the company, whatever its answer; console requests are not calls. Calls are counted in memory and written every few seconds, so the current day can lag slightly. #134: `quotas` gives the company's API calls per minute and per UTC day (enforced: over either, an API call answers 429 with `Retry-After`) with today's calls, and its device ingest rate and burst with the messages waiting in its ingest backlog; `stored` gives what the company keeps: its envelopes, the public scans of its fruits, its stored files (device attachments and uploaded documents) and their bytes. Allowed for tenant_admin, auditor and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The company's usage of its limits, its API calls per day and its quotas.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyUsage"
                },
                "example": {
                  "tenant": "coop-dl",
                  "warn_percent": 80,
                  "limits": [
                    {
                      "id": "members",
                      "used": 12,
                      "limit": 200,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "pending_links",
                      "used": 2,
                      "limit": 50,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "devices",
                      "used": 7,
                      "limit": null,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "api_tokens",
                      "used": 3,
                      "limit": 100,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "api_clients",
                      "used": 1,
                      "limit": 50,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "webhooks",
                      "used": 17,
                      "limit": 20,
                      "warning": true,
                      "reached": false
                    }
                  ],
                  "api_calls": [
                    {
                      "day": "2026-10-11",
                      "calls": 1520
                    },
                    {
                      "day": "2026-10-10",
                      "calls": 1873
                    },
                    {
                      "day": "2026-10-09",
                      "calls": 0
                    }
                  ],
                  "quotas": {
                    "api_per_minute": 1200,
                    "api_per_day": 500000,
                    "api_calls_today": 1520,
                    "api_day_warning": false,
                    "api_day_reached": false,
                    "ingest_per_second": 100,
                    "ingest_burst": 3000,
                    "ingest_backlog": 0
                  },
                  "stored": {
                    "envelopes": 184220,
                    "scans": 52310,
                    "attachments": 1730,
                    "storage_bytes": 412876800
                  }
                },
                "x-sdk-example": {
                  "tenant": "coop-dl",
                  "warn_percent": 80,
                  "limits": [
                    {
                      "id": "members",
                      "used": 12,
                      "limit": 200,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "pending_links",
                      "used": 2,
                      "limit": 50,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "devices",
                      "used": 7,
                      "limit": null,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "api_tokens",
                      "used": 3,
                      "limit": 100,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "api_clients",
                      "used": 1,
                      "limit": 50,
                      "warning": false,
                      "reached": false
                    },
                    {
                      "id": "webhooks",
                      "used": 17,
                      "limit": 20,
                      "warning": true,
                      "reached": false
                    }
                  ],
                  "api_calls": [
                    {
                      "day": "2026-10-11",
                      "calls": 1520
                    },
                    {
                      "day": "2026-10-10",
                      "calls": 1873
                    },
                    {
                      "day": "2026-10-09",
                      "calls": 0
                    }
                  ]
                }
              }
            },
            "x-sdk-description": "The company's usage of its limits and its API calls per day."
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, auditor and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused; operators are refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "SELF-2-5 (#194). For the selected company (X-Tenant): how much of each per-company limit it uses, counted by the same query the limit checks before a create, against the limit the backend enforces, and its API calls on each of the last 14 UTC days. Counts only; another company's records never count. An entry warns from `warn_percent` of its limit and is `reached` at the limit (the next create is refused). An API call is a request authenticated by an API token or an API client's access token of the company, whatever its answer; console requests are not calls. Calls are counted in memory and written every few seconds, so the current day can lag slightly; no daily quota is enforced. Allowed for tenant_admin, auditor and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators are refused (403)."
      }
    },
    "/v1/company/overview": {
      "get": {
        "operationId": "getCompanyOverview",
        "summary": "Read the selected company's overview",
        "description": "#274. For the selected company (X-Tenant): the counts its admins monitor on the admin home (open alerts, messages waiting for review, recalls, devices and gateways, calibrations and certifications ending, requests and changes waiting, today's work in the Vietnam calendar day, lots by status, shipments, its people and its usage), each section with `state`. Counts and the company's own codes only; another company's records never count. Computed at most every 30 seconds: the server serves one answer for `max_age_s` seconds after `generated_at`. Read-only and not audited (a read). `no-store`. Allowed for tenant_admin, auditor (`view` auditor: without the sections only admins may open) and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and lab users are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the console's admin home.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The company's overview.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyOverview"
                },
                "example": {
                  "tenant": "coop-dl",
                  "generated_at": "2026-10-17T07:32:05Z",
                  "max_age_s": 30,
                  "day": {
                    "date": "2026-10-17",
                    "starts_at": "2026-10-16T17:00:00Z",
                    "time_zone": "Asia/Ho_Chi_Minh"
                  },
                  "view": "admin",
                  "sections": {
                    "alerts": {
                      "state": "ok",
                      "open": 7,
                      "open_high": 2
                    },
                    "quarantine": {
                      "state": "ok",
                      "waiting": 3,
                      "capped": false,
                      "oldest_received_at": "2026-10-16T22:10:00Z"
                    },
                    "recalls": {
                      "state": "ok",
                      "recalled": 0,
                      "withdrawn": 1,
                      "notices_pending": 0
                    },
                    "fleet": {
                      "state": "ok",
                      "devices_active": 42,
                      "devices_ready": 39,
                      "devices_not_ready": 3,
                      "devices_pending_approval": 1,
                      "gateways_active": 4,
                      "gateways_silent": 0,
                      "calibrations_expired": 0,
                      "calibrations_expiring": 2,
                      "harvest_keys_pending": 0
                    },
                    "certifications": {
                      "state": "ok",
                      "expired": 0,
                      "expiring": 1
                    },
                    "today": {
                      "state": "ok",
                      "lots_created": 6,
                      "lots_capped": false,
                      "harvest_kg": 1840.5,
                      "harvest_areas": 3,
                      "messages": 51230,
                      "messages_capped": false,
                      "sessions_count": 1,
                      "sessions_open": [
                        {
                          "id": "ses-01",
                          "lot": "L-2026-0412",
                          "facility": "ph1",
                          "line": "1"
                        }
                      ]
                    },
                    "lots": {
                      "state": "ok",
                      "by_status": {
                        "draft": 1,
                        "open": 2,
                        "paused": 0,
                        "closed": 5,
                        "packed": 9,
                        "shipped": 120,
                        "recalled": 0,
                        "withdrawn": 1
                      }
                    },
                    "shipments": {
                      "state": "ok",
                      "open": 2,
                      "departed_7d": 5,
                      "recent_open": [
                        {
                          "code": "SHP-0091",
                          "created_at": "2026-10-16T03:00:00Z"
                        }
                      ]
                    },
                    "requests": {
                      "state": "ok",
                      "public_reports_open": 0,
                      "grower_requests_open": 1,
                      "grower_requests_due_soon": 0,
                      "personal_data_open": 0
                    },
                    "approvals": {
                      "state": "ok",
                      "second_admin_waiting": 0
                    },
                    "team": {
                      "state": "ok",
                      "members_active": 9,
                      "invitations_pending": 2,
                      "invitations_expiring": 1
                    },
                    "integrations": {
                      "state": "ok",
                      "webhooks_disabled": 0
                    },
                    "email": {
                      "state": "ok",
                      "failed_24h": 0,
                      "failed_kinds": []
                    },
                    "usage": {
                      "state": "ok",
                      "limits": [
                        {
                          "id": "members",
                          "used": 9,
                          "limit": 200,
                          "warning": false,
                          "reached": false
                        }
                      ],
                      "quotas": {
                        "api_per_day": 500000,
                        "api_calls_today": 1200,
                        "api_day_warning": false,
                        "api_day_reached": false
                      },
                      "api_calls": [
                        {
                          "day": "2026-10-17",
                          "calls": 1200
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, auditor and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused; operators and lab users are refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/company/logo": {
      "get": {
        "operationId": "getCompanyLogo",
        "summary": "Download the selected company's logo",
        "description": "SELF-1-5 (#186). Readers as for the profile. Staff only: no public page shows the logo yet. The Content-Type is sniffed from the bytes (PNG or JPEG), never taken from the upload.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "responses": {
          "200": {
            "description": "The logo's bytes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Content-Type-Options": {
                "description": "Always `nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "Always `inline`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Security-Policy": {
                "description": "Always `default-src 'none'; sandbox`.",
                "schema": {
                  "type": "string"
                }
              },
              "Cache-Control": {
                "description": "`private, no-cache`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "image/png": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "image/png"
                },
                "example": "(binary PNG bytes, starting 89 50 4E 47 0D 0A 1A 0A)"
              },
              "image/jpeg": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "image/jpeg"
                },
                "example": "(binary JPEG bytes, starting FF D8 FF)"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The company has no logo (or does not exist).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: logo",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "putCompanyLogo",
        "summary": "Set the selected company's logo",
        "description": "SELF-1-5 (#186). Company admins; a platform admin through X-Tenant. The body is the image itself: PNG or JPEG (never SVG), at most 256 KiB and 1024 x 1024 pixels. The type is checked by the file's magic bytes, which must match the Content-Type; the bytes must hash to `sha256`. Stored as an attachment of the company (the attachments store). The profile must be saved first. Audited (`company.logo.update`: the hash, media type, size and dimensions, never the bytes).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "sha256",
            "in": "query",
            "required": true,
            "description": "SHA-256 of the body: exactly 64 lowercase hex characters.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "image/png": {
              "schema": {
                "type": "string",
                "contentMediaType": "image/png",
                "format": "binary"
              },
              "example": "(binary PNG bytes, starting 89 50 4E 47 0D 0A 1A 0A)"
            },
            "image/jpeg": {
              "schema": {
                "type": "string",
                "contentMediaType": "image/jpeg",
                "format": "binary"
              },
              "example": "(binary JPEG bytes, starting FF D8 FF)"
            }
          }
        },
        "responses": {
          "200": {
            "description": "Stored; the profile now names this logo.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyLogoStored"
                },
                "example": {
                  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "media_type": "image/png",
                  "size": 20480,
                  "width": 512,
                  "height": 256
                }
              }
            }
          },
          "400": {
            "description": "A malformed sha256, an image whose header cannot be read or that is larger than 1024 x 1024 pixels, a missing or malformed Content-Length, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_hash": {
                    "value": {
                      "error": "invalid hash: sha256 is 64 lowercase hex characters",
                      "code": "invalid_hash"
                    }
                  },
                  "invalid_logo": {
                    "value": {
                      "error": "invalid logo: at most 1024 x 1024 pixels",
                      "code": "invalid_logo"
                    }
                  },
                  "bad_content_length": {
                    "value": {
                      "error": "bad content length",
                      "code": "bad_content_length"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin_not_allowed": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named a company (X-Tenant) that does not exist. A member names only its own companies (any other is 403 tenant not allowed), so another company's profile is never reached.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The company has no saved profile yet: save it first.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "no company profile: save the company profile before its logo",
                  "code": "no_company_profile"
                }
              }
            }
          },
          "413": {
            "description": "The logo is over 256 KiB (or the body over 1 MiB).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "logo_too_large": {
                    "value": {
                      "error": "logo too large: at most 256 KiB",
                      "code": "logo_too_large"
                    }
                  },
                  "body_too_large": {
                    "value": {
                      "error": "body too large",
                      "code": "body_too_large"
                    }
                  }
                }
              }
            }
          },
          "415": {
            "description": "A Content-Type other than image/png or image/jpeg, or bytes whose magic is not that type's.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unsupported_media_type": {
                    "value": {
                      "error": "unsupported media type: a logo is image/png or image/jpeg",
                      "code": "unsupported_media_type"
                    }
                  },
                  "content_does_not_match_the_media_type": {
                    "value": {
                      "error": "content does not match the media type",
                      "code": "content_does_not_match_the_media_type"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "The body does not hash to `sha256`; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "hash mismatch",
                  "code": "hash_mismatch"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/audit": {
      "get": {
        "operationId": "listAudit",
        "summary": "Audit log of the caller's tenant",
        "description": "Append-only audit rows of the caller's tenant, newest first, with keyset pagination: the company's activity log (SELF-1-7, #188). Every request that reaches the handler of a mutating route writes exactly one row (ingest and broker authorization are exempt). Rows cannot be changed or deleted: there is no route for it and the table refuses it. A successful sign-in is filed under the company the session first acts for (the user's first membership); a failed sign-in carries no company and appears in no company's log. Each item names who the actor is (`actor_kind`, `actor_name`); CropPath staff (platform admins) acting for the company are `support`. Filters combine (every one given must match). Allowed for auditor, tenant_admin and platform_admin.",
        "tags": [
          "audit"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "entity",
            "in": "query",
            "required": false,
            "description": "Only rows about this entity type.",
            "schema": {
              "type": "string"
            },
            "example": "envelope"
          },
          {
            "name": "actor",
            "in": "query",
            "required": false,
            "description": "Only rows by this actor.",
            "schema": {
              "type": "string"
            },
            "example": "admin@coop.example"
          },
          {
            "name": "entity_id",
            "in": "query",
            "required": false,
            "description": "Only rows about this record id (for example a lot code). An id longer than 128 characters is matched as its stored SHA-256 form. At most 512 characters.",
            "schema": {
              "type": "string",
              "maxLength": 512
            },
            "example": "LO-260928-014"
          },
          {
            "name": "action_prefix",
            "in": "query",
            "required": false,
            "description": "Only rows whose action starts with one of these comma-separated prefixes (at most 30; lowercase dotted words, for example `lot.,carton.` or `export.`).",
            "schema": {
              "type": "string"
            },
            "example": "lot.,session."
          },
          {
            "name": "since",
            "in": "query",
            "required": false,
            "description": "Only rows at or after this time: an ISO 8601 date or date-time (+07:00 when it has no offset).",
            "schema": {
              "type": "string"
            },
            "example": "2026-10-01"
          },
          {
            "name": "until",
            "in": "query",
            "required": false,
            "description": "Only rows before this time (exclusive), as `since`; it must be after `since`.",
            "schema": {
              "type": "string"
            },
            "example": "2026-10-11T00:00:00+07:00"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6NDJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of audit rows.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuditPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 42,
                      "at": 1790000000.5,
                      "actor": "admin@coop.example",
                      "tenant": "coop-dl",
                      "action": "envelope.review",
                      "entity": "envelope",
                      "entity_id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                      "before_hash": "9b0f1d6a2c7e4b3f8a5d0c9e1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c",
                      "after": {
                        "status": 200,
                        "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                        "decision": "approve",
                        "result": "accepted"
                      },
                      "request_id": "req-7f3a",
                      "ip_hash": "c3a1e07d94b2f58a61d0e7c4b9f3a2d8e5c17b60f4a9d2e3b8c5f1a7d0e4b962",
                      "actor_kind": "member",
                      "actor_name": "Nguyễn Văn An"
                    }
                  ],
                  "next_cursor": "eyJpZCI6NDJ9"
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, a malformed filter (action prefix, since, until, a range whose until is not after since, a record id over 512 characters), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_action_prefix": {
                    "value": {
                      "error": "bad action prefix",
                      "code": "bad_action_prefix"
                    }
                  },
                  "bad_since": {
                    "value": {
                      "error": "bad since",
                      "code": "bad_since"
                    }
                  },
                  "bad_until": {
                    "value": {
                      "error": "bad until",
                      "code": "bad_until"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range",
                      "code": "bad_range"
                    }
                  },
                  "bad_entity_id": {
                    "value": {
                      "error": "bad entity id",
                      "code": "bad_entity_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operator and lab) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/audit.csv": {
      "get": {
        "operationId": "getAuditCsv",
        "summary": "Activity log of the caller's tenant (CSV)",
        "description": "The rows GET /v1/audit lists for the same filters, newest first, as a CSV download (SELF-1-7, #188): at most 10,000 rows per file; when more match, `X-Next-Cursor` is the `cursor` of the next file. An audited read (`export.audit`: which filters were set, by name, the parsed range and action prefixes, and the row count), downloaded as an attachment, never cached. Allowed for auditor, tenant_admin and platform_admin acting for the tenant; another tenant's rows never appear.",
        "tags": [
          "audit"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "entity",
            "in": "query",
            "required": false,
            "description": "Only rows about this entity type.",
            "schema": {
              "type": "string"
            },
            "example": "envelope"
          },
          {
            "name": "actor",
            "in": "query",
            "required": false,
            "description": "Only rows by this actor.",
            "schema": {
              "type": "string"
            },
            "example": "admin@coop.example"
          },
          {
            "name": "entity_id",
            "in": "query",
            "required": false,
            "description": "Only rows about this record id (for example a lot code). An id longer than 128 characters is matched as its stored SHA-256 form. At most 512 characters.",
            "schema": {
              "type": "string",
              "maxLength": 512
            },
            "example": "LO-260928-014"
          },
          {
            "name": "action_prefix",
            "in": "query",
            "required": false,
            "description": "Only rows whose action starts with one of these comma-separated prefixes (at most 30; lowercase dotted words, for example `lot.,carton.` or `export.`).",
            "schema": {
              "type": "string"
            },
            "example": "lot.,session."
          },
          {
            "name": "since",
            "in": "query",
            "required": false,
            "description": "Only rows at or after this time: an ISO 8601 date or date-time (+07:00 when it has no offset).",
            "schema": {
              "type": "string"
            },
            "example": "2026-10-01"
          },
          {
            "name": "until",
            "in": "query",
            "required": false,
            "description": "Only rows before this time (exclusive), as `since`; it must be after `since`.",
            "schema": {
              "type": "string"
            },
            "example": "2026-10-11T00:00:00+07:00"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous file's `X-Next-Cursor`; omitted for the first file.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6NDJ9"
          }
        ],
        "responses": {
          "200": {
            "description": "CSV with a header row (id, time_utc, actor, actor_kind, actor_name, action, entity, entity_id, status, error, request_id; CRLF line ends), then one row per audit row. time_utc is ISO 8601 UTC. A text cell starting with =, +, -, @, a tab or a carriage return gets a leading ' so a spreadsheet never runs it as a formula.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Next-Cursor": {
                "description": "The cursor of the next file; absent on the last.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "id,time_utc,actor,actor_kind,actor_name,action,entity,entity_id,status,error,request_id\r\n42,2026-10-10T01:30:00Z,admin@coop.example,member,Nguyễn Văn An,lot.seal,lot,LO-260928-014,200,,req-7f3a\r\n"
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a malformed filter (action prefix, since, until, a range whose until is not after since, a record id over 512 characters), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_action_prefix": {
                    "value": {
                      "error": "bad action prefix",
                      "code": "bad_action_prefix"
                    }
                  },
                  "bad_since": {
                    "value": {
                      "error": "bad since",
                      "code": "bad_since"
                    }
                  },
                  "bad_until": {
                    "value": {
                      "error": "bad until",
                      "code": "bad_until"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range",
                      "code": "bad_range"
                    }
                  },
                  "bad_entity_id": {
                    "value": {
                      "error": "bad entity id",
                      "code": "bad_entity_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operator and lab) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/login": {
      "post": {
        "operationId": "login",
        "summary": "Sign in with email and password",
        "description": "Opens a server session and sets the session cookie. When an Origin header is sent it must be allowed. A previous session cookie presented on this request is revoked. Unknown user, wrong password, disabled and locked accounts all answer the same 401. SELF-1-6 (#187): for an account with two-step sign-in a correct password answers 202 with a login ticket instead (no session, no cookie, and the email's count of wrong attempts is not cleared); the code step opens the session.",
        "tags": [
          "auth"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LoginRequest"
              },
              "example": {
                "email": "alice@coop.example",
                "password": "correct horse battery"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Signed in. Send `csrf_token` as `X-CSRF-Token` on unsafe methods.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuthSession"
                },
                "example": {
                  "user": {
                    "id": 1,
                    "email": "alice@coop.example",
                    "display_name": "Alice"
                  },
                  "memberships": [
                    {
                      "tenant": "coop-dl",
                      "role": "tenant_admin",
                      "facilities": null,
                      "lab_id": null
                    }
                  ],
                  "csrf_token": "q3Vb0mXl2sQ"
                }
              }
            }
          },
          "202": {
            "description": "SELF-1-6 (#187): the password is right and the account has two-step sign-in. No session and no cookie yet: send the ticket and a code to POST /v1/auth/login/second-factor.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SecondFactorChallenge"
                },
                "example": {
                  "second_factor": "required",
                  "ticket": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGl2",
                  "expires_at": 1790086700.0
                }
              }
            }
          },
          "400": {
            "description": "email or password missing or not a string, or the body is not a JSON object.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "email and password are required",
                  "code": "email_and_password_are_required"
                }
              }
            }
          },
          "401": {
            "description": "Credentials refused.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "invalid credentials",
                  "code": "invalid_credentials"
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many login attempts from this client address (per-IP token bucket: bursts of 20, then 10 a minute). The Origin, the body and the credentials were not checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "Too many password hashes are running; retry after the delay.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "busy, retry",
                  "code": "busy_retry"
                }
              }
            }
          }
        }
      }
    },
    "/v1/auth/login/second-factor": {
      "post": {
        "operationId": "completeSecondFactor",
        "summary": "Finish a two-step sign-in with a code",
        "description": "SELF-1-6 (#187). Anonymous, like login: the login ticket of POST /v1/auth/login (202) and the 6-digit code from the authenticator app, or one unused backup code, open the session (cookie, `csrf_token`), in one transaction with the audit row (`auth.login`; a refusal is `auth.login.second_factor.failed`; never the ticket or the code). A code is accepted for the current 30-second step or one either side, and never twice for an account. A wrong code counts on the ticket (5 end it) and towards the email's login lockout; a locked email is refused whatever the code. A backup code works once. Takes a token from the login rate-limit bucket before anything else. When an Origin header is sent it must be allowed.",
        "tags": [
          "auth"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SecondFactorLogin"
              },
              "example": {
                "ticket": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGl2",
                "code": "492039"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Signed in. Send `csrf_token` as `X-CSRF-Token` on unsafe methods.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SecondFactorSession"
                },
                "example": {
                  "user": {
                    "id": 1,
                    "email": "alice@coop.example",
                    "display_name": "Alice"
                  },
                  "memberships": [
                    {
                      "tenant": "coop-dl",
                      "role": "tenant_admin",
                      "facilities": null,
                      "lab_id": null
                    }
                  ],
                  "csrf_token": "q3Vb0mXl2sQ",
                  "second_factor": "code",
                  "backup_codes_left": 10
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, no code and no backup code, both, or one that is not text; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "code_required": {
                    "value": {
                      "error": "code is required: the 6-digit code from the app, or a backup code",
                      "code": "code_is_required"
                    }
                  },
                  "both": {
                    "value": {
                      "error": "send code or backup_code, not both",
                      "code": "send_code_or_backup_code_not_both"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "The ticket is unknown, expired, used or out of attempts (start again with the password), or the code is wrong, already used, or refused (locked email, disabled account, password changed since the ticket).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "expired": {
                    "value": {
                      "error": "sign-in expired: enter your password again",
                      "code": "sign_in_expired"
                    }
                  },
                  "invalid_code": {
                    "value": {
                      "error": "invalid code",
                      "code": "invalid_code"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "429": {
            "description": "Too many sign-in attempts from this client address (the login bucket). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK) or it does not decrypt the secret, so a code cannot be checked (a backup code still works); or busy (no password hashing slot free in time). Nothing changed and nothing is let through on the password alone; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "kek": {
                    "value": {
                      "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                      "code": "issuer_keys_unavailable"
                    }
                  },
                  "busy": {
                    "value": {
                      "error": "busy, retry",
                      "code": "busy_retry"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/logout": {
      "post": {
        "operationId": "logout",
        "summary": "End the current session",
        "description": "Revokes the session and clears the cookie. Unsafe method: needs `X-CSRF-Token` and an allowed Origin.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "204": {
            "description": "Signed out. No body; the Set-Cookie header clears the cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/me": {
      "get": {
        "operationId": "getCurrentSession",
        "summary": "Who am I",
        "description": "The signed-in user, all memberships, the CSRF token, and the tenant and roles the request acts for (X-Tenant selects among memberships). SELF-1-6 (#187): `two_factor` tells the console whether this user's two-step sign-in is on, and whether this session must set it up before acting for the selected company.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The current session.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Me"
                },
                "example": {
                  "user": {
                    "id": 1,
                    "email": "alice@coop.example",
                    "display_name": "Alice"
                  },
                  "memberships": [
                    {
                      "tenant": "coop-dl",
                      "role": "tenant_admin",
                      "facilities": null,
                      "lab_id": null
                    }
                  ],
                  "csrf_token": "q3Vb0mXl2sQ",
                  "tenant": "coop-dl",
                  "roles": [
                    "tenant_admin"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant). Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/password": {
      "post": {
        "operationId": "changePassword",
        "summary": "Change the signed-in user's password",
        "description": "Revokes every session of the user (this one included) and opens a fresh one: the response carries the new CSRF token and a new Set-Cookie. A wrong current password counts towards the login lockout. The fresh session keeps this session's last password proof: a password change never counts as a recent sign-in for the operations that need one (call `POST /v1/auth/reauth`). #187: an account with two-step sign-in also sends `code` (or `backup_code`); a wrong one counts towards the login lockout like a wrong password, and the code is used up.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PasswordChangeRequest"
              },
              "example": {
                "current_password": "correct horse battery",
                "new_password": "another long passphrase"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Password changed; continue on the fresh session.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PasswordChanged"
                },
                "example": {
                  "csrf_token": "Zk1pQ8w2Ls"
                }
              }
            }
          },
          "400": {
            "description": "Body fields missing or not strings, new password too short or too long, or the current password is wrong; for an account with two-step sign-in, the code is missing, or the current password or the code is wrong.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missing": {
                    "value": {
                      "error": "current_password and new_password are required",
                      "code": "current_password_and_new_password_are_required"
                    }
                  },
                  "weak": {
                    "value": {
                      "error": "password must be at least 12 characters",
                      "code": "password_must_be_at_least_12_characters"
                    }
                  },
                  "wrong_current": {
                    "value": {
                      "error": "current password is incorrect",
                      "code": "current_password_is_incorrect"
                    }
                  },
                  "code_required": {
                    "value": {
                      "error": "code is required: the 6-digit code from the app, or a backup code",
                      "code": "code_is_required"
                    }
                  },
                  "wrong_code": {
                    "value": {
                      "error": "current password or code is incorrect",
                      "code": "current_password_or_code_is_incorrect"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "Too many password hashes are running; retry after the delay. Or (#187) a code was sent and the server's key-encryption key is missing: two-step sign-in is unavailable and the password is not changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "busy, retry",
                  "code": "busy_retry"
                }
              }
            }
          }
        }
      }
    },
    "/v1/auth/reauth": {
      "post": {
        "operationId": "reauthenticate",
        "summary": "Prove the signed-in user's password again",
        "description": "SELF-1-2 (#183). Records that this session proved its password now. Operations that create credentials (and, later, change who may act for the company) refuse a session whose last proof is more than 10 minutes old with 401 `reauthentication_required`; the browser then calls this operation and repeats the request. A wrong password counts towards the login lockout, and a locked account is refused whatever the password. Audited (`auth.reauth`, in the same transaction; never the password). Unsafe method: needs `X-CSRF-Token` and an allowed Origin. SELF-1-6 (#187): an account with two-step sign-in also sends `code` (or `backup_code`); a wrong one counts towards the lockout like a wrong password, and a right one also counts as this session's second factor proof. Step-up (#87): for such an account, a right code (or backup code) here also lets this session revoke signing, lab and issuer keys, recall or withdraw lots and add market limits for 5 minutes; those operations answer 401 `mfa_step_up_required` once it is older (or the password proof is older than 10 minutes).",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReauthRequest"
              },
              "example": {
                "password": "correct horse battery"
              }
            }
          }
        },
        "responses": {
          "204": {
            "description": "Password confirmed for this session. No body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            }
          },
          "400": {
            "description": "The password is missing or not a string, or it is wrong (or the account is locked after too many wrong passwords); for an account with two-step sign-in, the code is missing, or the password or the code is wrong; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missing": {
                    "value": {
                      "error": "password is required",
                      "code": "password_is_required"
                    }
                  },
                  "wrong": {
                    "value": {
                      "error": "password is incorrect",
                      "code": "password_is_incorrect"
                    }
                  },
                  "code_required": {
                    "value": {
                      "error": "code is required: the 6-digit code from the app, or a backup code",
                      "code": "code_is_required"
                    }
                  },
                  "wrong_code": {
                    "value": {
                      "error": "password or code is incorrect",
                      "code": "password_or_code_is_incorrect"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "Too many password hashes are running; retry after the delay.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "busy, retry",
                  "code": "busy_retry"
                }
              }
            }
          }
        },
        "x-sdk-description": "SELF-1-2 (#183). Records that this session proved its password now. Operations that create credentials (and, later, change who may act for the company) refuse a session whose last proof is more than 10 minutes old with 401 `reauthentication_required`; the browser then calls this operation and repeats the request. A wrong password counts towards the login lockout, and a locked account is refused whatever the password. Audited (`auth.reauth`, in the same transaction; never the password). Unsafe method: needs `X-CSRF-Token` and an allowed Origin. SELF-1-6 (#187): an account with two-step sign-in also sends `code` (or `backup_code`); a wrong one counts towards the lockout like a wrong password, and a right one also counts as this session's second factor proof."
      }
    },
    "/v1/auth/sessions": {
      "get": {
        "operationId": "listMySessions",
        "summary": "The signed-in user's devices (live sessions)",
        "description": "SELF-2-1 (#190). Every live session of the signed-in user, in every company they work for (a session belongs to the person, not to a company): the browser and system, when it was opened and last used (to the minute), and which one is making the request. Never a token, its hash, an IP address or the raw user agent. Session routes are open to every signed-in user, whatever the role, and act on that user's own sessions only.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The live sessions.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SignedInSessionList"
                },
                "example": {
                  "items": [
                    {
                      "id": 42,
                      "browser": "Chrome",
                      "os": "Windows",
                      "mobile": false,
                      "created_at": 1790060400,
                      "last_seen_at": 1790086380,
                      "current": true
                    },
                    {
                      "id": 37,
                      "browser": "Safari",
                      "os": "iOS",
                      "mobile": true,
                      "created_at": 1789899960,
                      "last_seen_at": 1789999980,
                      "current": false
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/sessions/revoke-others": {
      "post": {
        "operationId": "revokeMyOtherSessions",
        "summary": "Sign out everywhere else",
        "description": "SELF-2-1 (#190). Ends every session of the signed-in user except the one making the request, in every company (a lost or shared device). The devices are signed out from their next request on. Audited (`auth.session.revoke_others`, in the same transaction, with how many were ended). Repeating it ends nothing more (200, `sessions_revoked` 0). Unsafe method: needs `X-CSRF-Token` and an allowed Origin. Session routes are open to every signed-in user, whatever the role, and act on that user's own sessions only.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "Every other session ended.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SessionsRevoked"
                },
                "example": {
                  "sessions_revoked": 2
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/sessions/{id}/revoke": {
      "post": {
        "operationId": "revokeMySession",
        "summary": "Sign out one of the signed-in user's other devices",
        "description": "SELF-2-1 (#190). Ends one live session of the signed-in user (from listMySessions); that device is signed out from its next request on. The session making the request is ended by signing out (logout), not here (400 `current_session`). Another user's session, or one already ended or expired, answers 404 like a missing one. Audited (`auth.session.revoke`, in the same transaction). Unsafe method: needs `X-CSRF-Token` and an allowed Origin. Session routes are open to every signed-in user, whatever the role, and act on that user's own sessions only.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The session's id (from listMySessions).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "37"
          }
        ],
        "responses": {
          "200": {
            "description": "The session ended.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SignedInSessionRevoked"
                },
                "example": {
                  "id": 37,
                  "revoked": true
                }
              }
            }
          },
          "400": {
            "description": "The session making the request (sign out instead), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "current_session": {
                    "value": {
                      "error": "current session: sign out to end the session you are using",
                      "code": "current_session"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No live session of the signed-in user with that id (another user's session answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 37",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/email-settings": {
      "get": {
        "operationId": "getMyEmailSettings",
        "summary": "The signed-in person's email setting",
        "description": "#270. Whether the signed-in person gets the notification, alert and recall emails, the language of their emails, and whether this server sends email at all (`delivery`: SMTP configured; the console then says a new one-time link was emailed too, otherwise that it must be passed on by hand). Session routes are open to every signed-in user, whatever the role, and act on that user's own setting only. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The setting.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EmailSettings"
                },
                "example": {
                  "notifications": true,
                  "language": "vi",
                  "delivery": false
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "updateMyEmailSettings",
        "summary": "Turn the signed-in person's notification emails on or off",
        "description": "#270. Sets whether the signed-in person gets the notification, alert and recall emails, and their emails' language (the console sends its own). Invitation and password emails are always sent. Audited (`auth.email_settings.update`, in the same transaction: the prior setting's hash and the new one). Unsafe method: needs `X-CSRF-Token` and an allowed Origin. Session routes are open to every signed-in user, whatever the role, and act on that user's own setting only. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EmailSettingsUpdate"
              },
              "example": {
                "notifications": false,
                "language": "en"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Saved; the new setting.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EmailSettings"
                },
                "example": {
                  "notifications": false,
                  "language": "en",
                  "delivery": false
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, `notifications` missing or not a boolean, an unknown language, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "notifications": {
                    "value": {
                      "error": "notifications must be true or false",
                      "code": "notifications_must_be_true_or_false"
                    }
                  },
                  "language": {
                    "value": {
                      "error": "language must be one of: vi, en, zh-Hans",
                      "code": "language_must_be_one_of"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/password/recover": {
      "post": {
        "operationId": "recoverPassword",
        "summary": "Forgot password: set a new one with a two-step backup code",
        "description": "SELF-2-2 (#191). Anonymous, like login, and only for an account with two-step sign-in: the sign-in email, one unused backup code of the account and a new password set the password. In one transaction the backup code is used up, the password is stored, every session of the account is ended and its pending sign-ins are cancelled, with the audit row (`auth.password.recover`; a refusal is `auth.password.recover.failed`; never the code or a password). No session is opened and no cookie is set: the next sign-in asks for the new password and then the second step. An unknown email, an account without two-step sign-in, a disabled account, a wrong, used or malformed backup code and a locked email all get the same 400 answer after the same work, and every one but a locked email counts towards the email's login lockout. Takes a token from the login rate-limit bucket (per client address) before anything else, and one from a bucket keyed by the email named (5 an hour) before any password work. When an Origin header is sent it must be allowed.",
        "tags": [
          "auth"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PasswordRecoveryRequest"
              },
              "example": {
                "email": "alice@coop.example",
                "backup_code": "abcd-efgh-ijkl-mnop",
                "new_password": "another long passphrase"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The password is changed and every session of the account ended. No session is opened: sign in with the new password, then the second step.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PasswordRecovered"
                },
                "example": {
                  "backup_codes_left": 9,
                  "second_factor": "required"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing or non-text email, backup_code or new_password, or a new password that breaks the policy (checked before anything else); or the email and backup code do not fit an account with two-step sign-in (one answer whatever the reason); or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "refused": {
                    "value": {
                      "error": "email or backup code is incorrect",
                      "code": "email_or_backup_code_is_incorrect"
                    }
                  },
                  "missing": {
                    "value": {
                      "error": "email, backup_code and new_password are required",
                      "code": "email_backup_code_and_new_password_are_required"
                    }
                  },
                  "weak": {
                    "value": {
                      "error": "password must be at least 12 characters",
                      "code": "password_must_be_at_least_12_characters"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "429": {
            "description": "Too many attempts from this client address (the login bucket), or for this email (5 an hour). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "503": {
            "description": "Busy (no password hashing slot free in time). Nothing changed; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "busy, retry",
                  "code": "busy_retry"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/two-factor/setup": {
      "post": {
        "operationId": "setUpTwoFactor",
        "summary": "Start setting up the authenticator app",
        "description": "SELF-1-6 (#187). A new secret (160 bits) for the signed-in user's authenticator app, as text and as an otpauth URI for a QR code, in this response only; it is stored encrypted (AES-256-GCM under AGRITRACE_ISSUER_KEK, bound to the user) and is on only once POST /v1/auth/two-factor/confirm checks a code from it. Starting again replaces a setup that was not confirmed. Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`auth.two_factor.setup`; never the secret). Unsafe method: needs `X-CSRF-Token` and an allowed Origin.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The secret, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TwoFactorSetup"
                },
                "example": {
                  "secret": "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP",
                  "otpauth_uri": "otpauth://totp/CropPath:alice@coop.example?secret=JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP&issuer=CropPath",
                  "issuer": "CropPath",
                  "account": "alice@coop.example",
                  "digits": 6,
                  "period": 30
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "session": {
                    "value": {
                      "error": "not authenticated",
                      "code": "not_authenticated"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check, and to a session that has not proved a second factor yet (two_factor_required never answers here).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "Two-step sign-in is already on: turn it off (POST /v1/auth/two-factor/disable, with `set_up_again` for a new phone) first.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "already on: turn two-step sign-in off before setting it up again",
                  "code": "already_on"
                }
              }
            }
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK), or the stored secret does not decrypt with it: two-step sign-in cannot be checked or set up, and nothing is let through on the password alone. Retry after `Retry-After` seconds once it is configured.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                  "code": "issuer_keys_unavailable"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/two-factor/confirm": {
      "post": {
        "operationId": "confirmTwoFactor",
        "summary": "Turn the authenticator app on with its first code",
        "description": "SELF-1-6 (#187). Checks a code from the secret POST /v1/auth/two-factor/setup returned and turns two-step sign-in on: from the next sign-in a code is asked after the password. Returns 10 backup codes, in this response only. This session counts as having proved a second factor; every other session of the account ends. Audited (`auth.two_factor.enable`, in the same transaction; never a code). Unsafe method: needs `X-CSRF-Token` and an allowed Origin.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TwoFactorCode"
              },
              "example": {
                "code": "492039"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "On. The backup codes, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BackupCodes"
                },
                "example": {
                  "backup_codes": [
                    "k3xq-7mfa-2pzd-q4ve",
                    "a7hn-35sk-wqzr-t2bm",
                    "uj4c-6pde-mb3x-7fkr",
                    "q2wv-zyt5-4hna-kcpe",
                    "n6ft-rm3a-x7qd-s5bj",
                    "e4pk-2wvc-hy6m-zr3t",
                    "c5ad-kqmx-7nrj-w2ze",
                    "t3vy-hb6q-p4sm-x5ka",
                    "z7rm-e2nk-4bhp-dq6w",
                    "m5jd-ws3t-q7ac-2kyn"
                  ]
                }
              }
            }
          },
          "400": {
            "description": "The code is missing or wrong, or the body is not a JSON object; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "missing": {
                    "value": {
                      "error": "code is required",
                      "code": "code_is_required"
                    }
                  },
                  "invalid": {
                    "value": {
                      "error": "invalid code",
                      "code": "invalid_code"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check, and to a session that has not proved a second factor yet (two_factor_required never answers here).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "No setup to confirm: start with POST /v1/auth/two-factor/setup.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "nothing to confirm: start the setup again",
                  "code": "nothing_to_confirm"
                }
              }
            }
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK) or it does not decrypt the secret, so a code cannot be checked (a backup code still works); or busy (no password hashing slot free in time). Nothing changed and nothing is let through on the password alone; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "kek": {
                    "value": {
                      "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                      "code": "issuer_keys_unavailable"
                    }
                  },
                  "busy": {
                    "value": {
                      "error": "busy, retry",
                      "code": "busy_retry"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/two-factor/disable": {
      "post": {
        "operationId": "disableTwoFactor",
        "summary": "Turn the authenticator app off",
        "description": "SELF-1-6 (#187). Needs the password and a current code (or a backup code); a wrong one counts towards the login lockout. Refused (409) while the account must use two-step sign-in (a platform admin, a company admin after the deadline, a member of a company that requires it), unless `set_up_again` (a new phone: this session sets the app up again at once). Removes the secret and the backup codes, and every session of the account loses its proof of a second factor: where two-step sign-in is required, company routes answer 403 `two_factor_required` until the app is set up again. Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`auth.two_factor.disable`; never the password or a code). Unsafe method: needs `X-CSRF-Token` and an allowed Origin.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TwoFactorDisable"
              },
              "example": {
                "password": "correct horse battery",
                "code": "492039"
              }
            }
          }
        },
        "responses": {
          "204": {
            "description": "Off. No body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            }
          },
          "400": {
            "description": "A missing password, no code and no backup code, an unknown field, or the password or code is wrong (or the email is locked); or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "password": {
                    "value": {
                      "error": "password is required",
                      "code": "password_is_required"
                    }
                  },
                  "code": {
                    "value": {
                      "error": "code is required: the 6-digit code from the app, or a backup code",
                      "code": "code_is_required"
                    }
                  },
                  "wrong": {
                    "value": {
                      "error": "password or code is incorrect",
                      "code": "password_or_code_is_incorrect"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "session": {
                    "value": {
                      "error": "not authenticated",
                      "code": "not_authenticated"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check, and to a session that has not proved a second factor yet (two_factor_required never answers here).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "Two-step sign-in is not on, or this account must use it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_on": {
                    "value": {
                      "error": "not on: two-step sign-in is not set up for this account",
                      "code": "not_on"
                    }
                  },
                  "required": {
                    "value": {
                      "error": "two-step sign-in required: it cannot be turned off for this account",
                      "code": "two_step_sign_in_required"
                    }
                  }
                }
              }
            }
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK) or it does not decrypt the secret, so a code cannot be checked (a backup code still works); or busy (no password hashing slot free in time). Nothing changed and nothing is let through on the password alone; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "kek": {
                    "value": {
                      "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                      "code": "issuer_keys_unavailable"
                    }
                  },
                  "busy": {
                    "value": {
                      "error": "busy, retry",
                      "code": "busy_retry"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/backup-codes": {
      "post": {
        "operationId": "regenerateBackupCodes",
        "summary": "Get 10 new backup codes",
        "description": "SELF-1-6 (#187). Replaces every backup code of the signed-in user with 10 new ones, in this response only. Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`auth.backup_codes.regenerate`, in the same transaction; never a code). Unsafe method: needs `X-CSRF-Token` and an allowed Origin.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The new backup codes, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BackupCodes"
                },
                "example": {
                  "backup_codes": [
                    "k3xq-7mfa-2pzd-q4ve",
                    "a7hn-35sk-wqzr-t2bm",
                    "uj4c-6pde-mb3x-7fkr",
                    "q2wv-zyt5-4hna-kcpe",
                    "n6ft-rm3a-x7qd-s5bj",
                    "e4pk-2wvc-hy6m-zr3t",
                    "c5ad-kqmx-7nrj-w2ze",
                    "t3vy-hb6q-p4sm-x5ka",
                    "z7rm-e2nk-4bhp-dq6w",
                    "m5jd-ws3t-q7ac-2kyn"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "session": {
                    "value": {
                      "error": "not authenticated",
                      "code": "not_authenticated"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check, and to a session that has not proved a second factor yet (two_factor_required never answers here).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "Two-step sign-in is not on.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not on: two-step sign-in is not set up for this account",
                  "code": "not_on"
                }
              }
            }
          },
          "503": {
            "description": "Busy (no password hashing slot free in time): retry after `Retry-After` seconds; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "busy, retry",
                  "code": "busy_retry"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/links/inspect": {
      "post": {
        "operationId": "inspectAccountLink",
        "summary": "What a one-time link is for",
        "description": "SELF-1-3 (#184). Anonymous: whoever holds the link's token learns the company, role, email and expiry, and whether the email already has an account. Every unusable token (malformed, unknown, expired, used or revoked) is the same 404 `link_not_valid`, after the same single lookup by the token's hash. Takes a token from the login rate-limit bucket before anything else. A read: not audited.",
        "tags": [
          "auth"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AccountLinkToken"
              },
              "example": {
                "token": "agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The link's purpose and who it is for.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountLinkInfo"
                },
                "example": {
                  "purpose": "invite",
                  "company": "New Coop",
                  "role": "tenant_admin",
                  "email": "first.admin@coop-new.example",
                  "expires_at": 1790259200.5,
                  "account_exists": false
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No usable link: it expired, was used or revoked, or never existed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "link not valid",
                  "code": "link_not_valid"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many requests from this client address: these routes take from the login bucket (per-IP token bucket: bursts of 20, then 10 a minute). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/links/accept": {
      "post": {
        "operationId": "acceptAccountLink",
        "summary": "Accept a one-time link and sign in",
        "description": "SELF-1-3 (#184). Anonymous, like login. An invitation for an email without an account creates the account (the link's email, which cannot be changed; the password follows the login policy) and its membership; for an email with an account, `password` must be that account's password (a wrong one counts towards the login lockout, and 10 on one link revoke it) and only the membership is added. A reset link stores the new password and ends every other session of the account. The link is then used, and a session opens as with login (cookie, `csrf_token`), all in one transaction with the audit row (`account_link.accept`, in the company's log; never the token or the password). Every unusable token is the same 404 `link_not_valid`. Takes a token from the login rate-limit bucket before anything else. When an Origin header is sent it must be allowed. SELF-1-6 (#187): for an account with two-step sign-in the link is used but no session opens: 202 with a login ticket for POST /v1/auth/login/second-factor, so a link never skips the code step.",
        "tags": [
          "auth"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AccountLinkAccept"
              },
              "example": {
                "token": "agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                "password": "correct horse battery",
                "display_name": "Chi Lan"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Signed in. Send `csrf_token` as `X-CSRF-Token` on unsafe methods.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuthSession"
                },
                "example": {
                  "user": {
                    "id": 1,
                    "email": "alice@coop.example",
                    "display_name": "Alice"
                  },
                  "memberships": [
                    {
                      "tenant": "coop-dl",
                      "role": "tenant_admin",
                      "facilities": null,
                      "lab_id": null
                    }
                  ],
                  "csrf_token": "q3Vb0mXl2sQ"
                }
              }
            }
          },
          "202": {
            "description": "SELF-1-6 (#187): the password is right and the account has two-step sign-in. No session and no cookie yet: send the ticket and a code to POST /v1/auth/login/second-factor.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SecondFactorChallenge"
                },
                "example": {
                  "second_factor": "required",
                  "ticket": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGl2",
                  "expires_at": 1790086700.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field (the email cannot be changed), a missing password, a password outside 12 to 1,024 characters, a bad display name, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: email",
                      "code": "unknown_fields"
                    }
                  },
                  "password_required": {
                    "value": {
                      "error": "password is required",
                      "code": "password_is_required"
                    }
                  },
                  "weak": {
                    "value": {
                      "error": "password must be at least 12 characters",
                      "code": "password_must_be_at_least_12_characters"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "The email already has an account and the password is wrong, the email is locked after too many wrong passwords, or the account is disabled.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "invalid credentials",
                  "code": "invalid_credentials"
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "404": {
            "description": "No usable link: it expired, was used or revoked, or never existed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "link not valid",
                  "code": "link_not_valid"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The email got an account while the link was being accepted: open the link again.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "account created meanwhile: open the link again",
                  "code": "account_created_meanwhile"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many requests from this client address: these routes take from the login bucket (per-IP token bucket: bursts of 20, then 10 a minute). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "Too many password hashes are running; retry after the delay.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "busy, retry",
                  "code": "busy_retry"
                }
              }
            }
          }
        }
      }
    },
    "/v1/broker/authz": {
      "post": {
        "operationId": "authorizeBrokerAction",
        "summary": "EMQX HTTP authorization callback",
        "description": "Called by the MQTT broker, not by browsers. Authenticated with the shared broker secret as a bearer token. Answers 404 when the backend runs without a broker secret.",
        "tags": [
          "broker"
        ],
        "security": [
          {
            "broker": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BrokerAuthzRequest"
              },
              "example": {
                "username": "knk-1",
                "action": "publish",
                "topic": "agritrace/v1/coop-dl/ph1/knk-1/event"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The decision.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BrokerAuthzResult"
                },
                "example": {
                  "result": "allow"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "The broker secret is wrong or missing.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "invalid broker token",
                  "code": "invalid_broker_token"
                }
              }
            }
          },
          "404": {
            "description": "No broker secret is configured, so the route does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "no such route",
                  "code": "no_such_route"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/commands/{id}": {
      "get": {
        "operationId": "getCommand",
        "summary": "State of a command",
        "description": "Status moves pending, sent, then succeeded or failed. #242: an irrigation controller's actuation commands (run_zone, set_program) move pending, sent, then accepted and completed or aborted, or rejected, or expired; `channel=1` adds their kind, expiry, accepted time and reason. The parameter and those members are not part of the partner SDK clients (`x-not-in-sdk`).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "command_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Command id.",
            "schema": {
              "type": "string"
            },
            "example": "6f1c1c52-62a0-4f0e-8c3a-0b7e8d6d3e10"
          },
          {
            "name": "channel",
            "in": "query",
            "required": false,
            "description": "#242: `1` adds the command channel members (`kind`, `expires_at`, `reason`, `accepted_at`) to each command; `0` or none leaves them out and answers exactly the members answered before; any other value is refused (400 `bad channel`). It selects no commands: the status of an actuation command (accepted, rejected, completed, aborted, expired) is answered either way.",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "The recorded command.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Command"
                },
                "example": {
                  "id": "6f1c1c52-62a0-4f0e-8c3a-0b7e8d6d3e10",
                  "tenant": "coop-dl",
                  "site": "ph1",
                  "device_id": "knk-1",
                  "name": "set_model",
                  "params": {
                    "version": "m9"
                  },
                  "issued_by": "legacy-user",
                  "issued_at": 1790000000.5,
                  "status": "sent",
                  "result": null,
                  "completed_at": null
                }
              }
            }
          },
          "400": {
            "description": "`channel` not 0 or 1, or the X-Request-Id header is present and malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_channel": {
                    "value": {
                      "error": "bad channel",
                      "code": "bad_channel"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "$ref": "#/components/responses/BadRequestId"
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such command for this tenant.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 6f1c1c52-62a0-4f0e-8c3a-0b7e8d6d3e10",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Status moves pending, sent, then succeeded or failed."
      }
    },
    "/v1/command-keys": {
      "get": {
        "operationId": "listCommandKeys",
        "summary": "Public keys of the platform command key",
        "description": "#242: the public part of the platform command key, which signs every actuation command document (ES256 over the RFC 8785 canonical JSON of the document without `sig`; the document's `sig.kid` names the key). A controller is provisioned with it to verify the commands it receives. An empty `keys` list when the server has no command key: every actuation command is then refused. Allowed for tenant_admin and platform_admin (acting for the tenant), and an operator through a signed-in session or an operator API client, as issuing a command; auditors and labs are refused. Not audited (a read of public key material). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_command"
            ]
          }
        ],
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The platform command keys (at most one today).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CommandKeys"
                },
                "example": {
                  "keys": [
                    {
                      "kid": "platform-cmd-3b5e0c1d2a4f6e7d",
                      "alg": "ES256",
                      "jwk": {
                        "kty": "EC",
                        "crv": "P-256",
                        "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
                        "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
                      }
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (auditors, labs, an operator API token) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices": {
      "get": {
        "operationId": "listDevices",
        "summary": "Devices of the caller's tenant with their status read model",
        "description": "Devices ordered by id, with keyset pagination (at most 100 per page). Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only devices of its facilities: the device's facility, or its site when it has none).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of devices.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6Imtuay0xIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of devices.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DevicePage"
                },
                "example": {
                  "items": [
                    {
                      "device_id": "knk-1",
                      "tenant": "coop-dl",
                      "site": "ph1",
                      "facility": "VN-TGPH-021",
                      "profile": "vn.agritrace.durian-knocker",
                      "status": "active",
                      "display_name": "Knocker line 1",
                      "vendor_model": "SF-100",
                      "serial": "SF100-000123",
                      "created_at": 1790000000.5,
                      "commands": [
                        "calibrate",
                        "set_model",
                        "set_session"
                      ],
                      "last_seen": 1790003600.25,
                      "max_seq": 412,
                      "last_model": "m1",
                      "firmware": "1.4.2",
                      "battery_pct": 87.0,
                      "battery_v": 3.92,
                      "last_calibrated_at": 1789990000.0,
                      "ready": true,
                      "approval": "approved",
                      "approval_reason": null,
                      "approval_at": 1790000100.0
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createDevice",
        "summary": "Register a device",
        "description": "Registers an active device of the caller's tenant (never a body field). The id must be unused by every tenant's devices and gateways: an existing record is never replaced. Audited (`device.create`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DeviceCreate"
              },
              "example": {
                "device_id": "knk-1",
                "profile": "vn.agritrace.durian-knocker",
                "site": "ph1",
                "facility": "VN-TGPH-021",
                "display_name": "Knocker line 1",
                "vendor_model": "SF-100",
                "serial": "SF100-000123"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new device (never seen yet: no state, not ready).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Device"
                },
                "example": {
                  "device_id": "knk-1",
                  "tenant": "coop-dl",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "profile": "vn.agritrace.durian-knocker",
                  "status": "active",
                  "display_name": "Knocker line 1",
                  "vendor_model": "SF-100",
                  "serial": "SF100-000123",
                  "created_at": 1790000000.5,
                  "commands": [
                    "calibrate",
                    "set_model",
                    "set_session"
                  ],
                  "last_seen": null,
                  "max_seq": null,
                  "last_model": null,
                  "firmware": null,
                  "battery_pct": null,
                  "battery_v": null,
                  "last_calibrated_at": null,
                  "ready": false,
                  "approval": "approved",
                  "approval_reason": null,
                  "approval_at": 1790000100.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a malformed id or site, a profile that is not in the spec, a facility that is not one of the caller's tenant (missing and foreign alike), a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_device_id": {
                    "value": {
                      "error": "invalid device_id: 1 to 64 letters, digits, '.', '_' or '-', starting with a letter or digit",
                      "code": "invalid_device_id"
                    }
                  },
                  "unknown_profile": {
                    "value": {
                      "error": "unknown profile",
                      "code": "unknown_profile"
                    }
                  },
                  "unknown_facility": {
                    "value": {
                      "error": "unknown facility",
                      "code": "unknown_facility"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The id is used by a device or gateway (of any tenant; the owner is not revealed). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded). SELF-2-8 (#197): or the facility is a company's proposal CropPath has not approved yet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "device_id_taken": {
                    "value": {
                      "error": "device id taken",
                      "code": "device_id_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  },
                  "facility_not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ]
      }
    },
    "/v1/devices/{id}": {
      "get": {
        "operationId": "getDevice",
        "summary": "One device with its status read model",
        "description": "Same roles as the list; an operator reads only devices of its facilities.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "knk-1"
          }
        ],
        "responses": {
          "200": {
            "description": "The device.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Device"
                },
                "example": {
                  "device_id": "knk-1",
                  "tenant": "coop-dl",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "profile": "vn.agritrace.durian-knocker",
                  "status": "active",
                  "display_name": "Knocker line 1",
                  "vendor_model": "SF-100",
                  "serial": "SF100-000123",
                  "created_at": 1790000000.5,
                  "commands": [
                    "calibrate",
                    "set_model",
                    "set_session"
                  ],
                  "last_seen": 1790003600.25,
                  "max_seq": 412,
                  "last_model": "m1",
                  "firmware": "1.4.2",
                  "battery_pct": 87.0,
                  "battery_v": 3.92,
                  "last_calibrated_at": 1789990000.0,
                  "ready": true,
                  "approval": "approved",
                  "approval_reason": null,
                  "approval_at": 1790000100.0
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this tenant: a device of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateDevice",
        "summary": "Change a device's status or display fields",
        "description": "Sets `status` (`active` or `inactive`; ingest and the broker accept only active devices) and the display fields. The id, site, facility and profile cannot change. Audited (`device.update`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "knk-1"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DeviceUpdate"
              },
              "example": {
                "status": "inactive"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The device after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Device"
                },
                "example": {
                  "device_id": "knk-1",
                  "tenant": "coop-dl",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "profile": "vn.agritrace.durian-knocker",
                  "status": "inactive",
                  "display_name": "Knocker line 1",
                  "vendor_model": "SF-100",
                  "serial": "SF100-000123",
                  "created_at": 1790000000.5,
                  "commands": [
                    "calibrate",
                    "set_model",
                    "set_session"
                  ],
                  "last_seen": 1790003600.25,
                  "max_seq": 412,
                  "last_model": "m1",
                  "firmware": "1.4.2",
                  "battery_pct": 87.0,
                  "battery_v": 3.92,
                  "last_calibrated_at": 1789990000.0,
                  "ready": false,
                  "approval": "approved",
                  "approval_reason": null,
                  "approval_at": 1790000100.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an empty body, a field that cannot change, a status other than active or inactive, a value out of bounds, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "nothing_to_update": {
                    "value": {
                      "error": "nothing to update",
                      "code": "nothing_to_update"
                    }
                  },
                  "field_not_editable": {
                    "value": {
                      "error": "field not editable",
                      "code": "field_not_editable"
                    }
                  },
                  "invalid_status": {
                    "value": {
                      "error": "invalid status: active or inactive",
                      "code": "invalid_status"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this tenant: a device of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices/{id}/attachments/{sha256}": {
      "put": {
        "operationId": "uploadDeviceAttachment",
        "summary": "Upload the bytes of an attachment one of the device's envelopes references",
        "description": "For devices and gateways after the envelope was sent (the SDK's WAV upload, #24, targets this route). Accepted only when a stored envelope of device `{id}` lists `sha256` as an attachment; any bytes that hash to it are the signed content. Over mTLS the client certificate CN must be the device or the active gateway the envelope names (403 otherwise, the ingest rule); over plain HTTP (development) the reference and the hash are the whole check. Content-Type (parameters ignored) must equal the declared `mediaType` and be allowlisted; the body must hash to `sha256` and, when the envelope declares `size`, have that length; the bytes must carry the media type's signature. Already uploaded: 200 without reading the body. SELF-2-4 (#193): refused 403 `company_read_only` once the envelope's company is leaving CropPath or has left (storing the bytes would change its public fruit page). Never returns blob bytes. Not audited: the `attachments` row records the upload (see AUDIT_EXEMPT).",
        "tags": [
          "attachments"
        ],
        "security": [
          {
            "deviceMtls": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id of the envelope that references the blob.",
            "schema": {
              "type": "string"
            },
            "example": "knk-1"
          },
          {
            "name": "sha256",
            "in": "path",
            "required": true,
            "description": "SHA-256 of the blob: exactly 64 lowercase hex characters (anything else is 400 before any lookup).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/pdf": {
              "schema": {
                "type": "string",
                "contentMediaType": "application/pdf"
              },
              "example": "%PDF-1.7 ... (binary PDF bytes)"
            },
            "audio/wav": {
              "schema": {
                "type": "string",
                "contentMediaType": "audio/wav"
              },
              "example": "RIFF....WAVEfmt  ... (binary PCM WAV bytes)"
            },
            "image/jpeg": {
              "schema": {
                "type": "string",
                "contentMediaType": "image/jpeg"
              },
              "example": "(binary JPEG bytes, starting FF D8 FF)"
            },
            "image/png": {
              "schema": {
                "type": "string",
                "contentMediaType": "image/png"
              },
              "example": "(binary PNG bytes, starting 89 50 4E 47 0D 0A 1A 0A)"
            }
          }
        },
        "responses": {
          "200": {
            "description": "Already uploaded for this reference; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AttachmentStored"
                },
                "example": {
                  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "media_type": "audio/wav",
                  "size": 115244
                }
              }
            }
          },
          "201": {
            "description": "Stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AttachmentStored"
                },
                "example": {
                  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "media_type": "audio/wav",
                  "size": 115244
                }
              }
            }
          },
          "400": {
            "description": "Malformed sha256 in the path, a missing or malformed Content-Length, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_hash": {
                    "value": {
                      "error": "invalid hash",
                      "code": "invalid_hash"
                    }
                  },
                  "bad_content_length": {
                    "value": {
                      "error": "bad content length",
                      "code": "bad_content_length"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Over mTLS, the client certificate is neither the device nor the gateway the envelope names (`peer_mismatch`). SELF-2-4 (#193): or the envelope's company is leaving CropPath or has left (`company_read_only`): nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "peer_mismatch": {
                    "value": {
                      "error": "peer mismatch",
                      "code": "peer_mismatch"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No stored envelope of this device references the hash.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "415": {
            "description": "Media type outside the allowlist (audio/wav, image/jpeg, image/png, application/pdf) or not the one declared, or bytes that do not start with that type's signature.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unsupported_media_type": {
                    "value": {
                      "error": "unsupported media type",
                      "code": "unsupported_media_type"
                    }
                  },
                  "content_does_not_match_the_media_type": {
                    "value": {
                      "error": "content does not match the media type",
                      "code": "content_does_not_match_the_media_type"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "The body does not hash to `sha256`, or its length differs from the declared size; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "hash_mismatch": {
                    "value": {
                      "error": "hash mismatch",
                      "code": "hash_mismatch"
                    }
                  },
                  "size_mismatch": {
                    "value": {
                      "error": "size mismatch",
                      "code": "size_mismatch"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices/{id}/commands": {
      "get": {
        "operationId": "listDeviceCommands",
        "summary": "Commands sent to one device",
        "description": "The device's commands newest first (issued_at, then id), with keyset pagination (at most 200 per page). Same roles and scope as reading the device. #242: an irrigation controller's actuation commands (run_zone, set_program) move pending, sent, then accepted and completed or aborted, or rejected, or expired; `channel=1` adds their kind, expiry, accepted time and reason. The parameter and those members are not part of the partner SDK clients (`x-not-in-sdk`). #372: `name`, `status`, `from` and `to` filter the commands (the irrigation cockpit's command log); not part of the partner SDK clients either. A filter given empty (`?name=`) is no filter: an empty query value is dropped, as for every parameter.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "command_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "knk-1"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of commands.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6Imtuay0xIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "channel",
            "in": "query",
            "required": false,
            "description": "#242: `1` adds the command channel members (`kind`, `expires_at`, `reason`, `accepted_at`) to each command; `0` or none leaves them out and answers exactly the members answered before; any other value is refused (400 `bad channel`). It selects no commands: the status of an actuation command (accepted, rejected, completed, aborted, expired) is answered either way.",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          },
          {
            "name": "name",
            "in": "query",
            "required": false,
            "description": "#372: only the commands of this name (as the device profile declares it: `run_zone`, `set_program`, `calibrate`...); 400 `bad_name` for anything else than a lower-case token.",
            "schema": {
              "type": "string",
              "pattern": "^[a-z][a-z0-9_]{0,63}$"
            },
            "example": "run_zone",
            "x-not-in-sdk": true
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "#372: only the commands in this state; 400 `bad_status` for another value.",
            "schema": {
              "type": "string",
              "enum": [
                "accepted",
                "aborted",
                "completed",
                "expired",
                "failed",
                "pending",
                "rejected",
                "sent",
                "succeeded"
              ]
            },
            "example": "rejected",
            "x-not-in-sdk": true
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "#372: only the commands issued from the start of this farm-local date (Asia/Ho_Chi_Minh), `YYYY-MM-DD`, a year from 2000 to 9998; 400 `bad_from`.",
            "schema": {
              "type": "string",
              "format": "date"
            },
            "example": "2026-10-15",
            "x-not-in-sdk": true
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "#372: only the commands issued up to the end of this farm-local date, `YYYY-MM-DD`, a year from 2000 to 9998; 400 `bad_to`, and `bad_range` when it is before `from`.",
            "schema": {
              "type": "string",
              "format": "date"
            },
            "example": "2026-10-22",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "One page of commands.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CommandPage"
                },
                "example": {
                  "items": [
                    {
                      "id": "6f1c1c52-62a0-4f0e-8c3a-0b7e8d6d3e10",
                      "tenant": "coop-dl",
                      "site": "ph1",
                      "device_id": "knk-1",
                      "name": "set_model",
                      "params": {
                        "version": "m9"
                      },
                      "issued_by": "legacy-user",
                      "issued_at": 1790000000.5,
                      "status": "succeeded",
                      "result": {
                        "ok": true
                      },
                      "completed_at": 1790000003.0
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, `channel` not 0 or 1, a bad `name`, `status`, `from` or `to` filter (or `to` before `from`), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_channel": {
                    "value": {
                      "error": "bad channel",
                      "code": "bad_channel"
                    }
                  },
                  "bad_name": {
                    "value": {
                      "error": "bad name: a command name",
                      "code": "bad_name"
                    }
                  },
                  "bad_status": {
                    "value": {
                      "error": "bad status: accepted, aborted, completed, expired, failed, pending, rejected, sent, succeeded",
                      "code": "bad_status"
                    }
                  },
                  "bad_from": {
                    "value": {
                      "error": "bad from: a date YYYY-MM-DD",
                      "code": "bad_from"
                    }
                  },
                  "bad_to": {
                    "value": {
                      "error": "bad to: a date YYYY-MM-DD",
                      "code": "bad_to"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range: to is before from",
                      "code": "bad_range"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "bad_cursor": {
                      "value": {
                        "error": "bad cursor",
                        "code": "bad_cursor"
                      }
                    },
                    "bad_limit": {
                      "value": {
                        "error": "bad limit",
                        "code": "bad_limit"
                      }
                    },
                    "bad_request_id": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this tenant: a device of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "The device's commands newest first (issued_at, then id), with keyset pagination (at most 200 per page). Same roles and scope as reading the device."
      },
      "post": {
        "operationId": "issueDeviceCommand",
        "summary": "Send a command to a device",
        "description": "The command must be declared by the device profile and every param must be declared for it. The command is recorded before it is dispatched. A device of another tenant answers 404. #242: a command is issued only to an active, approved device reached by an active, approved key: one of its own, or that of an active, approved gateway at its site (409 `device_not_approved` otherwise, for every command). An actuation command (an irrigation controller's run_zone, a timed zone run, and set_program, a program lease) is sent as a command document signed with the platform command key (GET /v1/command-keys), which the controller verifies and enforces locally; every param it declares must be given within its declared range. Without a platform command key every actuation command is refused (503 `command_signing_unavailable`); config commands are not affected. A facility-scoped operator may issue calibrate, run_zone and set_program to a device of its facilities. A set_program whose program_version is not above the highest program_version of every set_program already recorded for the device (at any site, in any status) is refused (409 `program_version_not_increasing`): the controllers rely on strictly rising program versions per device. None of these refusals records a command, and the Idempotency-Key is not used up: a retry with the same key runs again. The 409 refusals and the 503 response are not part of the partner SDK clients (`x-not-in-sdk`).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_command"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "knk-1"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CommandRequest"
              },
              "example": {
                "name": "set_model",
                "params": {
                  "version": "m9"
                }
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "Recorded and handed to the transport.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CommandIssued"
                },
                "example": {
                  "id": "6f1c1c52-62a0-4f0e-8c3a-0b7e8d6d3e10"
                }
              }
            }
          },
          "400": {
            "description": "params is not an object, the command is not declared by the profile, a param is unknown, (#242) a param of the wrong type or outside its declared range or a required one missing, or the params are not strict JSON: a number that is not finite (NaN, Infinity) or a string holding U+0000 or a lone UTF-16 surrogate (U+D800-U+DFFF), anywhere in the params (invalid_params); or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "params": {
                    "value": {
                      "error": "params must be an object",
                      "code": "params_must_be_an_object"
                    }
                  },
                  "undeclared": {
                    "value": {
                      "error": "command 'reboot' not declared by profile vn.agritrace.durian-knocker",
                      "code": "command_reboot_not_declared_by_profile_vn_agritrace_durian_knocker"
                    }
                  },
                  "strict_json": {
                    "value": {
                      "error": "invalid params: a string holds U+0000",
                      "code": "invalid_params"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            },
            "x-sdk-description": "params is not an object, the command is not declared by the profile, a param is unknown, or the params are not strict JSON: a number that is not finite (NaN, Infinity) or a string holding U+0000 or a lone UTF-16 surrogate (U+D800-U+DFFF), anywhere in the params (invalid_params); or a malformed or repeated Idempotency-Key header."
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this tenant.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "#242: the device is not active and approved, or no active, approved key reaches it, neither one of its own nor that of an active, approved gateway at its site (`device_not_approved`); or a set_program's program_version is not above the highest one already recorded for the device (`program_version_not_increasing`); nothing was recorded. Or the Idempotency-Key's first request is still running (retry after `Retry-After` seconds), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "device_not_approved": {
                    "value": {
                      "error": "device not approved: knk-1",
                      "code": "device_not_approved"
                    }
                  },
                  "program_version_not_increasing": {
                    "value": {
                      "error": "program version not increasing: 7 is not above 7, the device's highest",
                      "code": "program_version_not_increasing"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "$ref": "#/components/responses/IdempotencyKeyConflict"
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "503": {
            "description": "#242: an actuation command was refused because the server has no platform command key to sign it with (`command_signing_unavailable`); nothing was recorded. Config commands are not affected.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "command signing unavailable",
                  "code": "command_signing_unavailable"
                }
              }
            },
            "x-not-in-sdk": true
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "The command must be declared by the device profile and every param must be declared for it. The command is recorded before it is dispatched. A device of another tenant answers 404."
      }
    },
    "/v1/envelopes/{id}/review": {
      "post": {
        "operationId": "reviewEnvelope",
        "summary": "Approve or reject a quarantined envelope",
        "description": "Approving makes the envelope accepted (counted in volumes, queued for outbound delivery). Rejecting marks it `rejected_after_review`. An envelope of another tenant answers 404.",
        "tags": [
          "integrity"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "review"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Envelope id.",
            "schema": {
              "type": "string"
            },
            "example": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReviewRequest"
              },
              "example": {
                "decision": "approve",
                "note": "weighed twice, scale re-calibrated"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The new status.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReviewResult"
                },
                "example": {
                  "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                  "status": "accepted"
                }
              }
            }
          },
          "400": {
            "description": "decision is not approve or reject, or the envelope is not quarantined; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_decision": {
                    "value": {
                      "error": "decision must be 'approve' or 'reject'",
                      "code": "decision_must_be_approve_or_reject"
                    }
                  },
                  "not_quarantined": {
                    "value": {
                      "error": "envelope is accepted, not quarantined",
                      "code": "envelope_is_accepted_not_quarantined"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such envelope for this tenant.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/envelopes": {
      "get": {
        "operationId": "listEnvelopes",
        "summary": "Device message log: stored envelopes, newest first",
        "description": "Every envelope ingest stored for the tenant (accepted, quarantined or rejected after review; never the messages refused before storage), newest first by received_at then id, with keyset pagination (default 50, at most 200 per page) and exact-match filters. A page that no index serves (a site, kind, event_type or lot filter, two of device, status and facility, or an operator scope of several facilities) reads at most 1000 envelopes of the tenant, so it may hold fewer items than the limit, even none, while `next_cursor` is set: follow `next_cursor` until it is null. Every filter value is checked before any query (400 `bad filter: <name>`). Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the envelopes recorded at its facilities); a lab is refused. Not audited.",
        "tags": [
          "envelopes"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "envelope_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhdCI6MTc5MDAwMDAwMC41fQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only this device's envelopes (exact device id).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "knk-1"
          },
          {
            "name": "site",
            "in": "query",
            "required": false,
            "description": "Only envelopes routed from this site (exact).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "ph1"
          },
          {
            "name": "facility",
            "in": "query",
            "required": false,
            "description": "Only envelopes recorded at this facility (exact code; the envelope context's `facility`).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "VN-TGPH-021"
          },
          {
            "name": "kind",
            "in": "query",
            "required": false,
            "description": "Only envelopes of this kind.",
            "schema": {
              "type": "string",
              "enum": [
                "telemetry",
                "event",
                "status"
              ]
            },
            "example": "event"
          },
          {
            "name": "event_type",
            "in": "query",
            "required": false,
            "description": "Only events of this type (exact).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "receive"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only envelopes in this state.",
            "schema": {
              "type": "string",
              "enum": [
                "accepted",
                "quarantined",
                "rejected_after_review"
              ]
            },
            "example": "quarantined"
          },
          {
            "name": "lot",
            "in": "query",
            "required": false,
            "description": "Only envelopes whose context names this lot (exact).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Only envelopes received at or after this time (epoch seconds, at most 6 decimals).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,11}(\\.[0-9]{1,6})?$"
            },
            "example": "1790000000"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "Only envelopes received before this time (epoch seconds, at most 6 decimals).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,11}(\\.[0-9]{1,6})?$"
            },
            "example": "1790086400.5"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of envelopes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EnvelopePage"
                },
                "example": {
                  "items": [
                    {
                      "id": "0c6f3a0e-5b8e-4a59-9e57-3d7c0f7d1a11",
                      "device_id": "scl-st",
                      "site": "ph1",
                      "facility": "VN-TGPH-021",
                      "seq": 41,
                      "kind": "event",
                      "event_type": "receive",
                      "event_time": "2026-09-28T08:56:02.120+07:00",
                      "received_at": 1790000000.5,
                      "status": "accepted",
                      "reasons": [],
                      "lot": "LO-260928-014"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor this API did not issue, a limit out of range, a bad filter value or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_filter": {
                    "value": {
                      "error": "bad filter: status",
                      "code": "bad_filter"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/envelopes/stream": {
      "get": {
        "operationId": "streamEnvelopes",
        "summary": "Live tail of the device message log (server-sent events)",
        "description": "A `text/event-stream` on the session stream's machinery (no Content-Length; `Cache-Control: no-cache`, `X-Accel-Buffering: no`; the connection closes when the stream ends). It starts with `retry: 2000`, then sends every envelope stored or reviewed after the resume point that passes the filters (the same as GET /v1/envelopes) as `id: <rx_seq>` / `event: envelope` / `data: {rx_seq, envelope}` (an EnvelopeSummary) in rx_seq order; a reviewed envelope is sent again with its new status. A `: hb` comment follows 15 s without output; there is no status or end event. The server polls once a second (at once while a backlog remains; one poll reads at most 1000 envelopes after the cursor, matching or not, and moves the cursor past them) and ends a stream after its lifetime (30 minutes by default; the client reconnects with `Last-Event-ID`). The resume point is the `Last-Event-ID` header when sent, else `after`, else the tenant's newest rx_seq. Envelopes stored before migration 15 have no rx_seq and are never streamed. The caps are shared with every other stream: at most 64 per backend process, half of them (32) for one tenant and 4 for one principal; above any of these the answer is 503 with `Retry-After: 2`. Authentication, the role check and the parameters are answered as JSON before any stream byte; the credential and the grant are checked again on every poll, so a logout, a revoked or expired session or API token, a disabled user, a password change or a lost grant ends the stream at once, and a grant moved to other facilities streams only those from the next poll. EventSource cannot send `X-Tenant`: a session principal streams its default tenant. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the envelopes recorded at its facilities); a lab is refused. Not audited.",
        "tags": [
          "envelopes"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "envelope_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "Last-Event-ID",
            "in": "header",
            "required": false,
            "description": "The id of the last event received (sent by EventSource on reconnect): resume after this rx_seq; a decimal integer from 0 to 2^63-1. Takes precedence over `after`.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,19}$"
            },
            "example": "413"
          },
          {
            "name": "after",
            "in": "query",
            "required": false,
            "description": "Send the envelopes stored or reviewed after this rx_seq; a decimal integer from 0 to 2^63-1. Without it (and without `Last-Event-ID`) the stream starts at the tenant's newest rx_seq: only what arrives from now on.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 9223372036854775807
            },
            "example": 412
          },
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only this device's envelopes (exact device id).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "knk-1"
          },
          {
            "name": "site",
            "in": "query",
            "required": false,
            "description": "Only envelopes routed from this site (exact).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "ph1"
          },
          {
            "name": "facility",
            "in": "query",
            "required": false,
            "description": "Only envelopes recorded at this facility (exact code; the envelope context's `facility`).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "VN-TGPH-021"
          },
          {
            "name": "kind",
            "in": "query",
            "required": false,
            "description": "Only envelopes of this kind.",
            "schema": {
              "type": "string",
              "enum": [
                "telemetry",
                "event",
                "status"
              ]
            },
            "example": "event"
          },
          {
            "name": "event_type",
            "in": "query",
            "required": false,
            "description": "Only events of this type (exact).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "receive"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only envelopes in this state.",
            "schema": {
              "type": "string",
              "enum": [
                "accepted",
                "quarantined",
                "rejected_after_review"
              ]
            },
            "example": "quarantined"
          },
          {
            "name": "lot",
            "in": "query",
            "required": false,
            "description": "Only envelopes whose context names this lot (exact).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128,
              "pattern": "^[^\\x00-\\x1f\\x7f]+$"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Only envelopes received at or after this time (epoch seconds, at most 6 decimals).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,11}(\\.[0-9]{1,6})?$"
            },
            "example": "1790000000"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "Only envelopes received before this time (epoch seconds, at most 6 decimals).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,11}(\\.[0-9]{1,6})?$"
            },
            "example": "1790086400.5"
          }
        ],
        "responses": {
          "200": {
            "description": "The event stream.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Accel-Buffering": {
                "description": "`no`: proxies must not buffer the stream.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string"
                },
                "example": "retry: 2000\n\nid: 8812\nevent: envelope\ndata: {\"rx_seq\":8812,\"envelope\":{\"id\":\"0c6f3a0e-5b8e-4a59-9e57-3d7c0f7d1a11\",\"device_id\":\"scl-st\",\"site\":\"ph1\",\"facility\":\"VN-TGPH-021\",\"seq\":41,\"kind\":\"event\",\"event_type\":\"receive\",\"event_time\":\"2026-09-28T08:56:02.120+07:00\",\"received_at\":1790000000.5,\"status\":\"accepted\",\"reasons\":[],\"lot\":\"LO-260928-014\"}}\n\n: hb\n\n"
              }
            }
          },
          "400": {
            "description": "A malformed `Last-Event-ID` or `after`, a bad filter value or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_last_event_id": {
                    "value": {
                      "error": "bad last event id",
                      "code": "bad_last_event_id"
                    }
                  },
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_filter": {
                    "value": {
                      "error": "bad filter: status",
                      "code": "bad_filter"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "Too many concurrent streams on this backend process, for the caller's tenant or for the caller (the caps every stream shares); poll GET /v1/envelopes instead and retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many streams",
                  "code": "too_many_streams"
                }
              }
            }
          }
        }
      }
    },
    "/v1/envelopes/{id}": {
      "get": {
        "operationId": "getEnvelope",
        "summary": "One stored envelope with its signed payload and signature status",
        "description": "The envelope's summary columns, its growing area, the signed payload exactly as stored and the signature checked again with the stored key it names (see EnvelopeDetail). Another tenant's envelope, or one outside an operator's facilities, answers 404 like a missing one. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the envelopes recorded at its facilities); a lab is refused. Not audited.",
        "tags": [
          "envelopes"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "envelope_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Envelope id.",
            "schema": {
              "type": "string"
            },
            "example": "0c6f3a0e-5b8e-4a59-9e57-3d7c0f7d1a11"
          }
        ],
        "responses": {
          "200": {
            "description": "The envelope.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EnvelopeDetail"
                },
                "example": {
                  "id": "0c6f3a0e-5b8e-4a59-9e57-3d7c0f7d1a11",
                  "device_id": "scl-st",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "seq": 41,
                  "kind": "event",
                  "event_type": "receive",
                  "event_time": "2026-09-28T08:56:02.120+07:00",
                  "received_at": 1790000000.5,
                  "status": "accepted",
                  "reasons": [],
                  "lot": "LO-260928-014",
                  "growing_area": null,
                  "payload": {
                    "spec": "agritrace.iot/1.0",
                    "id": "0c6f3a0e-5b8e-4a59-9e57-3d7c0f7d1a11",
                    "kind": "event",
                    "eventType": "receive",
                    "device": {
                      "id": "scl-st",
                      "profile": "vn.agritrace.scale-serial@1.0.0",
                      "gateway": "gw-01"
                    },
                    "seq": 41,
                    "time": "2026-09-28T08:56:02.120+07:00",
                    "readings": [
                      {
                        "capability": "mass.net",
                        "value": 3.42,
                        "unit": "kg"
                      }
                    ],
                    "context": {
                      "lot": "LO-260928-014",
                      "facility": "VN-TGPH-021"
                    },
                    "sig": {
                      "alg": "ES256",
                      "kid": "gw-01",
                      "value": "MEUCIQ"
                    }
                  },
                  "signature": {
                    "status": "valid",
                    "kid": "gw-01",
                    "key_status": "active"
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such envelope for this tenant (or outside the operator's facilities).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 0c6f3a0e-5b8e-4a59-9e57-3d7c0f7d1a11",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/facilities": {
      "get": {
        "operationId": "listFacilities",
        "summary": "Facilities of the caller's tenant",
        "description": "Facilities (packing houses) of the caller's tenant ordered by code, with keyset pagination. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the facilities of its memberships).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of facilities.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IlZOLVRHUEgtMDIxIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "admin_units",
            "in": "query",
            "required": false,
            "description": "#273: `1` adds the address by official code (`province_code`, `commune_code`, `admin_units_version`, `address_status`, `address_before_reform`, `address_candidates`, `commune`); `0` or none leaves them out and answers exactly as before; any other value is refused (400 `bad admin_units`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "One page of facilities.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityPage"
                },
                "example": {
                  "items": [
                    {
                      "code": "VN-TGPH-021",
                      "tenant": "coop-dl",
                      "name": "Tan Phu packing house",
                      "address": "Cai Lay, Tien Giang",
                      "province": "Tien Giang",
                      "district": "Cai Lay",
                      "gacc_phc_code": "VNPH-TG-021",
                      "lines": [
                        "L1",
                        "L2"
                      ],
                      "source": "manual",
                      "approved_at": null,
                      "slug": "vn-tgph-021",
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5,
                      "proposed_at": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, `admin_units` not 0 or 1, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_admin_units": {
                    "value": {
                      "error": "bad admin_units",
                      "code": "bad_admin_units"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "bad_cursor": {
                      "value": {
                        "error": "bad cursor",
                        "code": "bad_cursor"
                      }
                    },
                    "bad_limit": {
                      "value": {
                        "error": "bad limit",
                        "code": "bad_limit"
                      }
                    },
                    "bad_request_id": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createFacility",
        "summary": "Register a facility",
        "description": "Creates an unapproved facility (source `manual`) owned by the tenant the platform admin acts for (`X-Tenant`); the body cannot name another tenant. The code is unique across all tenants and cannot be changed later. The slug defaults to the lower-cased code. Audited (`facility.create`). Allowed for platform_admin only. #273: the address in Viet Nam is given by official code, `province_code` and `commune_code` from `getAdminUnits`; the server writes the official names (`district` null). The text fields `province` and `district` are deprecated (sunset 1 May 2027): a text-only address is still accepted, stores the record as not yet coded and answers with the `Deprecation`, `Sunset` and `Link` headers.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FacilityCreate"
              },
              "example": {
                "code": "VN-TGPH-021",
                "name": "Tan Phu packing house",
                "address": "Ấp 3, Ngũ Hiệp",
                "province_code": "82",
                "commune_code": "28516",
                "gacc_phc_code": "VNPH-TG-021",
                "lines": [
                  "L1",
                  "L2"
                ]
              },
              "x-sdk-example": {
                "code": "VN-TGPH-021",
                "name": "Tan Phu packing house",
                "address": "Cai Lay, Tien Giang",
                "province": "Tien Giang",
                "district": "Cai Lay",
                "gacc_phc_code": "VNPH-TG-021",
                "lines": [
                  "L1",
                  "L2"
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new facility.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              },
              "Deprecation": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. `@1792195200` (RFC 9745): the text-only address was deprecated at the start of 17 October 2026, UTC.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Sunset": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. `Sat, 01 May 2027 00:00:00 GMT` (RFC 8594): from then a text-only address in Viet Nam may be refused.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Link": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. `<https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"deprecation\", <https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"sunset\"`: the changelog entry that says what to send instead.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Facility"
                },
                "example": {
                  "code": "VN-TGPH-021",
                  "tenant": "coop-dl",
                  "name": "Tan Phu packing house",
                  "address": "Ấp 3, Ngũ Hiệp",
                  "province": "Tỉnh Đồng Tháp",
                  "district": null,
                  "gacc_phc_code": "VNPH-TG-021",
                  "lines": [
                    "L1",
                    "L2"
                  ],
                  "source": "manual",
                  "approved_at": null,
                  "slug": "vn-tgph-021",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "proposed_at": null
                },
                "x-sdk-example": {
                  "code": "VN-TGPH-021",
                  "tenant": "coop-dl",
                  "name": "Tan Phu packing house",
                  "address": "Cai Lay, Tien Giang",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "gacc_phc_code": "VNPH-TG-021",
                  "lines": [
                    "L1",
                    "L2"
                  ],
                  "source": "manual",
                  "approved_at": null,
                  "slug": "vn-tgph-021",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "proposed_at": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a code that does not look like VN-TGPH-021, a missing name, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header. #273: also a code that is not in the administrative units list in force (`admin_unit_unknown`), a commune that the list places in another province (`commune_not_in_province`), a district (`district_with_codes`) or a province name sent with the codes (`invalid_province`), or a malformed code or one code without the other (`invalid_province_code`, `invalid_commune_code`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_code": {
                    "value": {
                      "error": "invalid code: must look like VN-TGPH-021",
                      "code": "invalid_code"
                    }
                  },
                  "invalid_name": {
                    "value": {
                      "error": "invalid name: a string of at most 200 characters, not empty",
                      "code": "invalid_name"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "admin_unit_unknown": {
                    "value": {
                      "error": "admin unit unknown: commune 99999 is not in the official list vn-2026-10-17",
                      "code": "admin_unit_unknown"
                    }
                  },
                  "commune_not_in_province": {
                    "value": {
                      "error": "commune not in province: commune 00004 (Phường Ba Đình) is in province 01 (Thành phố Hà Nội), not in 82 (Tỉnh Đồng Tháp)",
                      "code": "commune_not_in_province"
                    }
                  },
                  "district_with_codes": {
                    "value": {
                      "error": "district with codes: Viet Nam has no district level since 2025-07-01; send it null",
                      "code": "district_with_codes"
                    }
                  },
                  "invalid_province": {
                    "value": {
                      "error": "invalid province: absent or null with the codes, the server writes the official name",
                      "code": "invalid_province"
                    }
                  },
                  "invalid_province_code": {
                    "value": {
                      "error": "invalid province_code: the official code, 2 digits as a string, sent with commune_code",
                      "code": "invalid_province_code"
                    }
                  },
                  "invalid_commune_code": {
                    "value": {
                      "error": "invalid commune_code: the official code, 5 digits as a string, sent with province_code",
                      "code": "invalid_commune_code"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "Invalid JSON, an unknown field, a code that does not look like VN-TGPH-021, a missing name, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "invalid_json": {
                      "value": {
                        "error": "invalid JSON",
                        "code": "invalid_json"
                      }
                    },
                    "invalid_code": {
                      "value": {
                        "error": "invalid code: must look like VN-TGPH-021",
                        "code": "invalid_code"
                      }
                    },
                    "invalid_name": {
                      "value": {
                        "error": "invalid name: a string of at most 200 characters, not empty",
                        "code": "invalid_name"
                      }
                    },
                    "unknown_field": {
                      "value": {
                        "error": "unknown field",
                        "code": "unknown_field"
                      }
                    },
                    "invalid_idempotency_key": {
                      "value": {
                        "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                        "code": "invalid_idempotency_key"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The code or slug is taken, or the acting tenant is not registered. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "code_taken": {
                    "value": {
                      "error": "facility code already exists",
                      "code": "facility_code_already_exists"
                    }
                  },
                  "slug_taken": {
                    "value": {
                      "error": "slug already in use",
                      "code": "slug_already_in_use"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not registered",
                      "code": "tenant_not_registered"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "503": {
            "description": "#273: `province_code` and `commune_code` were sent but the server has no administrative units list in force to check them (`administrative_units_catalog_unavailable`); nothing was written. A text-only address is not refused this way.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "administrative units catalog unavailable",
                  "code": "administrative_units_catalog_unavailable"
                }
              }
            },
            "x-not-in-sdk": true
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Creates an unapproved facility (source `manual`) owned by the tenant the platform admin acts for (`X-Tenant`); the body cannot name another tenant. The code is unique across all tenants and cannot be changed later. The slug defaults to the lower-cased code. Audited (`facility.create`). Allowed for platform_admin only."
      }
    },
    "/v1/facilities/{code}": {
      "get": {
        "operationId": "getFacility",
        "summary": "One facility",
        "description": "Same roles as the list; an operator reads only its own facilities.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          },
          {
            "name": "admin_units",
            "in": "query",
            "required": false,
            "description": "#273: `1` adds the address by official code (`province_code`, `commune_code`, `admin_units_version`, `address_status`, `address_before_reform`, `address_candidates`, `commune`); `0` or none leaves them out and answers exactly as before; any other value is refused (400 `bad admin_units`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "The facility.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Facility"
                },
                "example": {
                  "code": "VN-TGPH-021",
                  "tenant": "coop-dl",
                  "name": "Tan Phu packing house",
                  "address": "Cai Lay, Tien Giang",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "gacc_phc_code": "VNPH-TG-021",
                  "lines": [
                    "L1",
                    "L2"
                  ],
                  "source": "manual",
                  "approved_at": null,
                  "slug": "vn-tgph-021",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "proposed_at": null
                }
              }
            }
          },
          "400": {
            "description": "`admin_units` is not 0 or 1, or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_admin_units": {
                    "value": {
                      "error": "bad admin_units",
                      "code": "bad_admin_units"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "$ref": "#/components/responses/BadRequestId"
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this tenant: a facility of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateFacility",
        "summary": "Edit a facility",
        "description": "A tenant_admin may change name, address, province, district and lines; a platform_admin also gacc_phc_code and slug. The code is immutable; tenant, source and approved_at change only through platform paths. Edits keep the approval. Audited (`facility.update`). #273: the address in Viet Nam is given by official code, `province_code` and `commune_code` from `getAdminUnits`; the server writes the official names (`district` null). The text fields `province` and `district` are deprecated (sunset 1 May 2027): a text-only address is still accepted, stores the record as not yet coded and answers with the `Deprecation`, `Sunset` and `Link` headers.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FacilityUpdate"
              },
              "example": {
                "name": "Tan Phu packing house 2",
                "lines": [
                  "L1",
                  "L2",
                  "L3"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The facility after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Deprecation": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `@1792195200` (RFC 9745): the text-only address was deprecated at the start of 17 October 2026, UTC.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Sunset": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `Sat, 01 May 2027 00:00:00 GMT` (RFC 8594): from then a text-only address in Viet Nam may be refused.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Link": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `<https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"deprecation\", <https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"sunset\"`: the changelog entry that says what to send instead.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Facility"
                },
                "example": {
                  "code": "VN-TGPH-021",
                  "tenant": "coop-dl",
                  "name": "Tan Phu packing house",
                  "address": "Ấp 3, Ngũ Hiệp",
                  "province": "Tỉnh Đồng Tháp",
                  "district": null,
                  "gacc_phc_code": "VNPH-TG-021",
                  "lines": [
                    "L1",
                    "L2"
                  ],
                  "source": "manual",
                  "approved_at": null,
                  "slug": "vn-tgph-021",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "proposed_at": null
                },
                "x-sdk-example": {
                  "code": "VN-TGPH-021",
                  "tenant": "coop-dl",
                  "name": "Tan Phu packing house",
                  "address": "Cai Lay, Tien Giang",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "gacc_phc_code": "VNPH-TG-021",
                  "lines": [
                    "L1",
                    "L2"
                  ],
                  "source": "manual",
                  "approved_at": null,
                  "slug": "vn-tgph-021",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "proposed_at": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, the code in the body, a field the caller may not change, an empty body, a value out of bounds, or a bad X-Request-Id. #273: also a code that is not in the administrative units list in force (`admin_unit_unknown`), a commune that the list places in another province (`commune_not_in_province`), a district (`district_with_codes`) or a province name sent with the codes (`invalid_province`), or a malformed code or one code without the other (`invalid_province_code`, `invalid_commune_code`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "immutable": {
                    "value": {
                      "error": "code is immutable",
                      "code": "code_is_immutable"
                    }
                  },
                  "not_editable": {
                    "value": {
                      "error": "field not editable",
                      "code": "field_not_editable"
                    }
                  },
                  "empty": {
                    "value": {
                      "error": "nothing to update",
                      "code": "nothing_to_update"
                    }
                  },
                  "invalid_lines": {
                    "value": {
                      "error": "invalid lines: at most 32 distinct names of 1 to 32 characters",
                      "code": "invalid_lines"
                    }
                  },
                  "admin_unit_unknown": {
                    "value": {
                      "error": "admin unit unknown: commune 99999 is not in the official list vn-2026-10-17",
                      "code": "admin_unit_unknown"
                    }
                  },
                  "commune_not_in_province": {
                    "value": {
                      "error": "commune not in province: commune 00004 (Phường Ba Đình) is in province 01 (Thành phố Hà Nội), not in 82 (Tỉnh Đồng Tháp)",
                      "code": "commune_not_in_province"
                    }
                  },
                  "district_with_codes": {
                    "value": {
                      "error": "district with codes: Viet Nam has no district level since 2025-07-01; send it null",
                      "code": "district_with_codes"
                    }
                  },
                  "invalid_province": {
                    "value": {
                      "error": "invalid province: absent or null with the codes, the server writes the official name",
                      "code": "invalid_province"
                    }
                  },
                  "invalid_province_code": {
                    "value": {
                      "error": "invalid province_code: the official code, 2 digits as a string, sent with commune_code",
                      "code": "invalid_province_code"
                    }
                  },
                  "invalid_commune_code": {
                    "value": {
                      "error": "invalid commune_code: the official code, 5 digits as a string, sent with province_code",
                      "code": "invalid_commune_code"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "Invalid JSON, the code in the body, a field the caller may not change, an empty body, a value out of bounds, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "invalid_json": {
                      "value": {
                        "error": "invalid JSON",
                        "code": "invalid_json"
                      }
                    },
                    "immutable": {
                      "value": {
                        "error": "code is immutable",
                        "code": "code_is_immutable"
                      }
                    },
                    "not_editable": {
                      "value": {
                        "error": "field not editable",
                        "code": "field_not_editable"
                      }
                    },
                    "empty": {
                      "value": {
                        "error": "nothing to update",
                        "code": "nothing_to_update"
                      }
                    },
                    "invalid_lines": {
                      "value": {
                        "error": "invalid lines: at most 32 distinct names of 1 to 32 characters",
                        "code": "invalid_lines"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this tenant: a facility of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The slug is taken by another facility, or the facility has an issuer key (#34: its slug is its did:web path and never changes from then on).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "slug_taken": {
                    "value": {
                      "error": "slug already in use",
                      "code": "slug_already_in_use"
                    }
                  },
                  "slug_fixed": {
                    "value": {
                      "error": "slug fixed: the facility has issuer keys",
                      "code": "slug_fixed"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "503": {
            "description": "#273: `province_code` and `commune_code` were sent but the server has no administrative units list in force to check them (`administrative_units_catalog_unavailable`); nothing was written. A text-only address is not refused this way.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "administrative units catalog unavailable",
                  "code": "administrative_units_catalog_unavailable"
                }
              }
            },
            "x-not-in-sdk": true
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "A tenant_admin may change name, address, province, district and lines; a platform_admin also gacc_phc_code and slug. The code is immutable; tenant, source and approved_at change only through platform paths. Edits keep the approval. Audited (`facility.update`)."
      }
    },
    "/v1/facilities/{code}/approve": {
      "post": {
        "operationId": "approveFacility",
        "summary": "Approve a facility",
        "description": "Sets approved_at. Idempotent: approving an approved facility keeps the first approved_at. No request body. Audited (`facility.approve`). Allowed for platform_admin only, in the tenant it acts for.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The approved facility.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Facility"
                },
                "example": {
                  "code": "VN-TGPH-021",
                  "tenant": "coop-dl",
                  "name": "Tan Phu packing house",
                  "address": "Cai Lay, Tien Giang",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "gacc_phc_code": "VNPH-TG-021",
                  "lines": [
                    "L1",
                    "L2"
                  ],
                  "source": "manual",
                  "approved_at": 1790000100.0,
                  "slug": "vn-tgph-021",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000100.0,
                  "proposed_at": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this tenant: a facility of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/facilities/{code}/gln": {
      "get": {
        "operationId": "getFacilityGln",
        "summary": "A facility's GLN",
        "description": "#161: the facility's GS1 Global Location Number, null when it has none. Same roles as reading the facility; an operator reads only its own facilities. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          }
        ],
        "responses": {
          "200": {
            "description": "The facility's GLN.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityGln"
                },
                "example": {
                  "facility": "VN-TGPH-021",
                  "gln": "6141410000014"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "setFacilityGln",
        "summary": "Set, clear or allocate a facility's GLN",
        "description": "#161: the GLN names the facility as read point and business location in the lot's EPCIS documents (staff, and the public one issued at a later seal). Unique within the company. `allocate` takes the next GLN of the platform's GS1 company prefix (the deployment's AGRITRACE_GS1_COMPANY_PREFIX; 409 while none is configured). Same roles as editing the facility (tenant_admin, platform_admin acting for the company). Audited (`facility.gln.set`) in the company's activity log. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GlnChange"
              },
              "example": {
                "gln": "6141410000014"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The GLN as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityGln"
                },
                "example": {
                  "facility": "VN-TGPH-021",
                  "gln": "6141410000014"
                }
              }
            }
          },
          "400": {
            "description": "A body that is not {\"gln\": <13 digits> | null} or {\"allocate\": true}, a GLN whose check digit is wrong or that carries the platform's prefix (allocated only), invalid JSON or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: {\"gln\": \"<13 digits>\" | null} or {\"allocate\": true}",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_gln": {
                    "value": {
                      "error": "invalid gln: 13 digits with a valid GS1 check digit",
                      "code": "invalid_gln"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such record for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Another record of the company has that GLN; or no GS1 company prefix is configured (allocation), or every reference of it is allocated.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "gln_in_use": {
                    "value": {
                      "error": "gln already in use by another facility of the company",
                      "code": "gln_already_in_use_by_another_facility_of_the_company"
                    }
                  },
                  "prefix": {
                    "value": {
                      "error": "prefix not configured: the platform has no GS1 company prefix yet; enter a number of the company's own GS1 membership",
                      "code": "prefix_not_configured"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/facilities/{code}/certifications": {
      "get": {
        "operationId": "listFacilityCertifications",
        "summary": "A facility's packing-house certifications",
        "description": "#269: every packing-house certification of the facility (ISO 22000, FSSC 22000, BRCGS, IFS; at most 100, one page), newest `valid_from` first, each with its status on today's date in Viet Nam. Shown to the company's staff only: no trust tier and no public page uses them (architect decision on #269; ADR 0001). Same roles as reading the facility; an operator reads only its own facilities. Not audited (a read). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          }
        ],
        "responses": {
          "200": {
            "description": "The facility's certifications.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityCertificationList"
                },
                "example": {
                  "items": [
                    {
                      "id": 12,
                      "facility": "VN-TGPH-021",
                      "scheme": "BRCGS",
                      "number": "BRC-12345",
                      "issuer": "Bureau Veritas Certification",
                      "valid_from": "2026-03-01",
                      "valid_to": "2027-02-28",
                      "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
                      "created_at": 1790000000.5,
                      "ended_on": null,
                      "end_reason": null,
                      "ended_at": null,
                      "status": "valid"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createFacilityCertification",
        "summary": "Record a facility's packing-house certification",
        "description": "#269: records a certification of a packing-house scheme on the facility: its number, its certifier, its validity and the SHA-256 of the certificate document, which the company uploads first with PUT /v1/attachments/{sha256} (never public; the facility's readers read it through GET /v1/attachments/{sha256}). A facility proposal takes none until CropPath approves it (409 `facility not approved`, as for its GLN, lots and devices). The same scheme and number are recorded once per facility. Nothing is edited or deleted: end a certification instead. Shown to the company's staff only: no trust tier and no public page uses them (architect decision on #269; ADR 0001). Same roles as editing the facility (tenant_admin, platform_admin acting for the company). Audited (`facility.certification.create`) in the company's activity log. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FacilityCertificationCreate"
              },
              "example": {
                "scheme": "BRCGS",
                "number": "BRC-12345",
                "issuer": "Bureau Veritas Certification",
                "valid_from": "2026-03-01",
                "valid_to": "2027-02-28",
                "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The certification as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityCertification"
                },
                "example": {
                  "id": 12,
                  "facility": "VN-TGPH-021",
                  "scheme": "BRCGS",
                  "number": "BRC-12345",
                  "issuer": "Bureau Veritas Certification",
                  "valid_from": "2026-03-01",
                  "valid_to": "2027-02-28",
                  "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
                  "created_at": 1790000000.5,
                  "ended_on": null,
                  "end_reason": null,
                  "ended_at": null,
                  "status": "valid"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a scheme outside the list, a bad value, a certificate the company has not uploaded, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: status",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_scheme": {
                    "value": {
                      "error": "invalid scheme: one of ISO 22000, FSSC 22000, BRCGS, IFS",
                      "code": "invalid_scheme"
                    }
                  },
                  "invalid_evidence_sha256": {
                    "value": {
                      "error": "invalid evidence_sha256: upload the certificate first (PUT /v1/attachments/{sha256})",
                      "code": "invalid_evidence_sha256"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The facility is a proposal CropPath has not approved yet, has a certification of that scheme and number, or holds 100 certifications. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  },
                  "recorded": {
                    "value": {
                      "error": "certification already recorded",
                      "code": "certification_already_recorded"
                    }
                  },
                  "too_many": {
                    "value": {
                      "error": "too many certifications: a facility holds at most 100",
                      "code": "too_many_certifications"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/facilities/{code}/certifications/{id}/end": {
      "post": {
        "operationId": "endFacilityCertification",
        "summary": "End a facility's packing-house certification",
        "description": "#269: ends the certification from a day within its validity (withdrawn, suspended or replaced), with a reason; once, never undone (a mistake is ended and recorded again). Its status is `ended` from that day. Shown to the company's staff only: no trust tier and no public page uses them (architect decision on #269; ADR 0001). Same roles as editing the facility. Audited (`facility.certification.end`) in the company's activity log. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Certification id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FacilityCertificationEnd"
              },
              "example": {
                "ended_on": "2026-10-19",
                "reason": "Suspended by the certification body"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The certification after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityCertification"
                },
                "example": {
                  "id": 12,
                  "facility": "VN-TGPH-021",
                  "scheme": "BRCGS",
                  "number": "BRC-12345",
                  "issuer": "Bureau Veritas Certification",
                  "valid_from": "2026-03-01",
                  "valid_to": "2027-02-28",
                  "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
                  "created_at": 1790000000.5,
                  "ended_on": "2026-10-19",
                  "end_reason": "Suspended by the certification body",
                  "ended_at": 1790000100.5,
                  "status": "ended"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a day outside the validity, no reason, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_ended_on": {
                    "value": {
                      "error": "invalid ended_on: a day from valid_from to valid_to",
                      "code": "invalid_ended_on"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: 1 to 500 characters on one line",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this company (one of another company, or outside an operator's facilities, answers exactly like a missing one), or no such certification of the facility.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The certification was ended already. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "ended": {
                    "value": {
                      "error": "certification already ended",
                      "code": "certification_already_ended"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/facility-proposals": {
      "get": {
        "operationId": "listFacilityProposals",
        "summary": "The platform's facility proposal queue",
        "description": "SELF-2-8 (#197): every company's facility proposals waiting for CropPath, ordered by code, with keyset pagination, each with its company and who proposed it when. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of facilities.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IlZOLVRHUEgtMDIxIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the queue.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityProposalPage"
                },
                "example": {
                  "items": [
                    {
                      "code": "VN-TGPH-044",
                      "tenant": "coop-dl",
                      "tenant_name": "Coop DL",
                      "name": "Hoa Hung packing house",
                      "address": "Cai Be, Tien Giang",
                      "province": "Tien Giang",
                      "district": "Cai Be",
                      "lines": [
                        "A1"
                      ],
                      "slug": "vn-tgph-044",
                      "proposed_at": 1790000000.5,
                      "proposed_by": "admin@coop.example"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "proposeFacility",
        "summary": "Propose a facility of the company",
        "description": "SELF-2-8 (#197): a company admin proposes a facility (packing house) of the company it acts for; the body cannot name another company. The facility starts unapproved with proposed_at set, the default slug of its code (numbered when taken) and no GACC PHC code. Until CropPath approves it, no lot, shipment, device, gateway, harvest app key or signing key may name it (409 `facility not approved`), so it never reaches a label, a public page, a customs file or a trust tier. The code is unique across all companies and cannot be changed later; a company holds at most 20 proposals waiting for CropPath (409 `too many pending proposals`). Audited (`facility.propose`). Allowed for tenant_admin and platform_admin through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration registers codes. #273: the address in Viet Nam is given by official code, `province_code` and `commune_code` from `getAdminUnits`; the server writes the official names (`district` null). The text fields `province` and `district` are deprecated (sunset 1 May 2027): a text-only address is still accepted, stores the record as not yet coded and answers with the `Deprecation`, `Sunset` and `Link` headers.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FacilityProposalCreate"
              },
              "example": {
                "code": "VN-TGPH-044",
                "name": "Hoa Hung packing house",
                "address": "Ấp Hòa Hưng",
                "province_code": "82",
                "commune_code": "28516",
                "lines": [
                  "A1"
                ]
              },
              "x-sdk-example": {
                "code": "VN-TGPH-044",
                "name": "Hoa Hung packing house",
                "address": "Cai Be, Tien Giang",
                "province": "Tien Giang",
                "district": "Cai Be",
                "lines": [
                  "A1"
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The proposed facility, unapproved.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              },
              "Deprecation": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. `@1792195200` (RFC 9745): the text-only address was deprecated at the start of 17 October 2026, UTC.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Sunset": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. `Sat, 01 May 2027 00:00:00 GMT` (RFC 8594): from then a text-only address in Viet Nam may be refused.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Link": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province` or `district`, without `province_code` and `commune_code`), on every answer, errors included. `<https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"deprecation\", <https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"sunset\"`: the changelog entry that says what to send instead.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Facility"
                },
                "example": {
                  "code": "VN-TGPH-044",
                  "tenant": "coop-dl",
                  "name": "Hoa Hung packing house",
                  "address": "Ấp Hòa Hưng",
                  "province": "Tỉnh Đồng Tháp",
                  "district": null,
                  "gacc_phc_code": null,
                  "lines": [
                    "A1"
                  ],
                  "source": "manual",
                  "approved_at": null,
                  "slug": "vn-tgph-044",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "proposed_at": 1790000000.5
                },
                "x-sdk-example": {
                  "code": "VN-TGPH-044",
                  "tenant": "coop-dl",
                  "name": "Hoa Hung packing house",
                  "address": "Cai Be, Tien Giang",
                  "province": "Tien Giang",
                  "district": "Cai Be",
                  "gacc_phc_code": null,
                  "lines": [
                    "A1"
                  ],
                  "source": "manual",
                  "approved_at": null,
                  "slug": "vn-tgph-044",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "proposed_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a code that does not look like VN-TGPH-021, a missing name, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header. #273: also a code that is not in the administrative units list in force (`admin_unit_unknown`), a commune that the list places in another province (`commune_not_in_province`), a district (`district_with_codes`) or a province name sent with the codes (`invalid_province`), or a malformed code or one code without the other (`invalid_province_code`, `invalid_commune_code`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_code": {
                    "value": {
                      "error": "invalid code: must look like VN-TGPH-021",
                      "code": "invalid_code"
                    }
                  },
                  "invalid_name": {
                    "value": {
                      "error": "invalid name: a string of at most 200 characters, not empty",
                      "code": "invalid_name"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "admin_unit_unknown": {
                    "value": {
                      "error": "admin unit unknown: commune 99999 is not in the official list vn-2026-10-17",
                      "code": "admin_unit_unknown"
                    }
                  },
                  "commune_not_in_province": {
                    "value": {
                      "error": "commune not in province: commune 00004 (Phường Ba Đình) is in province 01 (Thành phố Hà Nội), not in 82 (Tỉnh Đồng Tháp)",
                      "code": "commune_not_in_province"
                    }
                  },
                  "district_with_codes": {
                    "value": {
                      "error": "district with codes: Viet Nam has no district level since 2025-07-01; send it null",
                      "code": "district_with_codes"
                    }
                  },
                  "invalid_province": {
                    "value": {
                      "error": "invalid province: absent or null with the codes, the server writes the official name",
                      "code": "invalid_province"
                    }
                  },
                  "invalid_province_code": {
                    "value": {
                      "error": "invalid province_code: the official code, 2 digits as a string, sent with commune_code",
                      "code": "invalid_province_code"
                    }
                  },
                  "invalid_commune_code": {
                    "value": {
                      "error": "invalid commune_code: the official code, 5 digits as a string, sent with province_code",
                      "code": "invalid_commune_code"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "Invalid JSON, an unknown field, a code that does not look like VN-TGPH-021, a missing name, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "invalid_json": {
                      "value": {
                        "error": "invalid JSON",
                        "code": "invalid_json"
                      }
                    },
                    "invalid_code": {
                      "value": {
                        "error": "invalid code: must look like VN-TGPH-021",
                        "code": "invalid_code"
                      }
                    },
                    "invalid_name": {
                      "value": {
                        "error": "invalid name: a string of at most 200 characters, not empty",
                        "code": "invalid_name"
                      }
                    },
                    "unknown_field": {
                      "value": {
                        "error": "unknown field",
                        "code": "unknown_field"
                      }
                    },
                    "invalid_idempotency_key": {
                      "value": {
                        "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                        "code": "invalid_idempotency_key"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The code is taken (by any company), or the acting company is not registered. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "code_taken": {
                    "value": {
                      "error": "facility code already exists",
                      "code": "facility_code_already_exists"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not registered",
                      "code": "tenant_not_registered"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "503": {
            "description": "#273: `province_code` and `commune_code` were sent but the server has no administrative units list in force to check them (`administrative_units_catalog_unavailable`); nothing was written. A text-only address is not refused this way.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "administrative units catalog unavailable",
                  "code": "administrative_units_catalog_unavailable"
                }
              }
            },
            "x-not-in-sdk": true
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "SELF-2-8 (#197): a company admin proposes a facility (packing house) of the company it acts for; the body cannot name another company. The facility starts unapproved with proposed_at set, the default slug of its code (numbered when taken) and no GACC PHC code. Until CropPath approves it, no lot, shipment, device, gateway, harvest app key or signing key may name it (409 `facility not approved`), so it never reaches a label, a public page, a customs file or a trust tier. The code is unique across all companies and cannot be changed later; a company holds at most 20 proposals waiting for CropPath (409 `too many pending proposals`). Audited (`facility.propose`). Allowed for tenant_admin and platform_admin through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration registers codes."
      }
    },
    "/v1/facility-proposals/{code}/approve": {
      "post": {
        "operationId": "approveFacilityProposal",
        "summary": "Approve a company's facility proposal (platform)",
        "description": "SELF-2-8 (#197): a platform admin approves a facility proposal of any company, setting its slug and GACC PHC code in the same change when given. 409 when the facility is not a company's proposal (approve it with POST /v1/facilities/{code}/approve), is already approved, or the slug is taken. Audited (`facility.proposal.approve`) in the proposing company's activity log. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-044"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FacilityProposalApproval"
              },
              "example": {
                "slug": "hoahung",
                "gacc_phc_code": "VNPH-TG-044"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The approved facility.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Facility"
                },
                "example": {
                  "code": "VN-TGPH-044",
                  "tenant": "coop-dl",
                  "name": "Hoa Hung packing house",
                  "address": "Cai Be, Tien Giang",
                  "province": "Tien Giang",
                  "district": "Cai Be",
                  "gacc_phc_code": "VNPH-TG-044",
                  "lines": [
                    "A1"
                  ],
                  "source": "manual",
                  "approved_at": 1790000300.0,
                  "slug": "hoahung",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000300.0,
                  "proposed_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad slug or GACC PHC code, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_slug": {
                    "value": {
                      "error": "invalid slug: lower-case letters and digits joined by single hyphens, at most 64 characters",
                      "code": "invalid_slug"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the proposing company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No facility has this code.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-044",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "Not a company's proposal, already approved, or the slug is taken. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_a_proposal": {
                    "value": {
                      "error": "facility is not a proposal",
                      "code": "facility_is_not_a_proposal"
                    }
                  },
                  "already_approved": {
                    "value": {
                      "error": "facility already approved",
                      "code": "facility_already_approved"
                    }
                  },
                  "slug_taken": {
                    "value": {
                      "error": "slug already in use",
                      "code": "slug_already_in_use"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/facility-proposals/{code}/reject": {
      "post": {
        "operationId": "rejectFacilityProposal",
        "summary": "Reject a company's facility proposal (platform)",
        "description": "SELF-2-8 (#197): a platform admin rejects a facility proposal of any company with a reason the company reads in its activity log. The proposal is deleted, so its code is free again (nothing can name a proposal). 409 when the facility is not a company's proposal or is already approved. Audited (`facility.proposal.reject`) in the proposing company's activity log. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-044"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FacilityProposalRejection"
              },
              "example": {
                "reason": "This code belongs to another company's packing house."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "What was rejected.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FacilityProposalRejected"
                },
                "example": {
                  "code": "VN-TGPH-044",
                  "tenant": "coop-dl",
                  "name": "Hoa Hung packing house",
                  "reason": "This code belongs to another company's packing house."
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing or too long reason, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: a string of 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the proposing company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No facility has this code.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-044",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "Not a company's proposal, or already approved. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_a_proposal": {
                    "value": {
                      "error": "facility is not a proposal",
                      "code": "facility_is_not_a_proposal"
                    }
                  },
                  "already_approved": {
                    "value": {
                      "error": "facility already approved",
                      "code": "facility_already_approved"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/product-gtins": {
      "get": {
        "operationId": "listProductGtins",
        "summary": "The company's trade item GTINs",
        "description": "#161: every trade item (product, variety, grade) the company registered with its GTIN, at most 500. Allowed for the company's readers (admins, auditors). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The trade items.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProductGtinList"
                },
                "example": {
                  "items": [
                    {
                      "product": "durian",
                      "variety": "Ri6",
                      "grade": null,
                      "gtin": "09520000000011",
                      "allocated": true,
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createProductGtin",
        "summary": "Register a trade item's GTIN",
        "description": "#161: the GTIN of a (product, variety, grade), allocated from the platform's GS1 company prefix (owner decision D2; 409 while none is configured), or a GTIN of the company's own GS1 membership. A lot created without a GTIN then takes the GTIN of its ungraded (product, variety). The item and the GTIN are each unique within the company. Allowed for tenant_admin and platform_admin acting for the company. Audited (`product_gtin.create`) in the company's activity log. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_edit"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProductGtinCreate"
              },
              "example": {
                "product": "durian",
                "variety": "Ri6"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The trade item registered.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProductGtin"
                },
                "example": {
                  "product": "durian",
                  "variety": "Ri6",
                  "grade": null,
                  "gtin": "09520000000011",
                  "allocated": true,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "An unknown or malformed field (a GTIN whose check digit is wrong or that carries the platform's prefix), invalid JSON, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_gtin": {
                    "value": {
                      "error": "invalid gtin: 14 digits with a valid GS1 check digit",
                      "code": "invalid_gtin"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The item or the GTIN is registered already, the company holds 500 items, no GS1 company prefix is configured; or the Idempotency-Key's first request is still running.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "item": {
                    "value": {
                      "error": "trade item already has a gtin",
                      "code": "trade_item_already_has_a_gtin"
                    }
                  },
                  "gtin": {
                    "value": {
                      "error": "gtin already in use by another trade item of the company",
                      "code": "gtin_already_in_use_by_another_trade_item_of_the_company"
                    }
                  },
                  "prefix": {
                    "value": {
                      "error": "prefix not configured: the platform has no GS1 company prefix yet; enter a number of the company's own GS1 membership",
                      "code": "prefix_not_configured"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/polygon-proposals": {
      "get": {
        "operationId": "listPolygonProposals",
        "summary": "Companies' growing-area boundary proposals (platform)",
        "description": "SENS-A1 (#224): every company's growing-area boundary changes waiting for CropPath, ordered by area code, with keyset pagination, each with its company, the proposed boundary and its SHA-256, who proposed it when, and the version in force. Allowed for platform_admin only (never an OAuth client). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of proposals.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IlZOLVRHT1ItMDM4NyJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the queue.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PolygonProposalPage"
                },
                "example": {
                  "items": [
                    {
                      "code": "VN-TGOR-0387",
                      "tenant": "coop-dl",
                      "tenant_name": "Coop DL",
                      "name": "Orchard 387",
                      "polygon": {
                        "type": "Polygon",
                        "coordinates": [
                          [
                            [
                              106.1,
                              10.4
                            ],
                            [
                              106.2,
                              10.4
                            ],
                            [
                              106.2,
                              10.5
                            ],
                            [
                              106.1,
                              10.5
                            ],
                            [
                              106.1,
                              10.4
                            ]
                          ]
                        ]
                      },
                      "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
                      "proposed_at": 1790007200.5,
                      "proposed_by": "admin@coop.example",
                      "current_version": 2,
                      "current_polygon_sha256": "3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a",
                      "current_polygon": {
                        "type": "Polygon",
                        "coordinates": [
                          [
                            [
                              106.1,
                              10.4
                            ],
                            [
                              106.15,
                              10.4
                            ],
                            [
                              106.15,
                              10.5
                            ],
                            [
                              106.1,
                              10.5
                            ],
                            [
                              106.1,
                              10.4
                            ]
                          ]
                        ]
                      }
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/polygon-proposals/{code}/approve": {
      "post": {
        "operationId": "approvePolygonProposal",
        "summary": "Approve a company's growing-area boundary proposal (platform)",
        "description": "SENS-A1 (#224): a platform admin approves the boundary change waiting on a growing area of any company, naming the SHA-256 of the proposal they reviewed. The proposal becomes the area's boundary and a new version, in force from now; earlier versions stay as they were. 409 when the area has no proposal waiting or the proposal is not the one reviewed (the company replaced it meanwhile). Audited (`growing_area.polygon.approve`, the version's number and SHA-256, never coordinates; the proposal's own row names who proposed it) in the area's company's activity log. Allowed for platform_admin only (never an OAuth client). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PolygonProposalApproval"
              },
              "example": {
                "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The new boundary version.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PolygonVersion"
                },
                "example": {
                  "growing_area": "VN-TGOR-0387",
                  "version": 2,
                  "polygon_sha256": "3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a",
                  "valid_from": 1790003600.0,
                  "origin": "proposal",
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  },
                  "proposed_at": 1790000000.5,
                  "proposed_by": "admin@coop.example",
                  "approved_by": "root@croppath.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing or malformed polygon_sha256, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "polygon_sha256_is_required": {
                    "value": {
                      "error": "polygon_sha256 is required: the SHA-256 of the proposal reviewed, or null for a removal",
                      "code": "polygon_sha256_is_required"
                    }
                  },
                  "invalid_polygon_sha256": {
                    "value": {
                      "error": "invalid polygon_sha256: 64 lower-case hex characters, or null",
                      "code": "invalid_polygon_sha256"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the proposing company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No growing area has this code.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "No boundary proposal is waiting, or the proposal is not the one reviewed. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "no_polygon_proposal": {
                    "value": {
                      "error": "no polygon proposal: the area has no boundary change waiting for approval",
                      "code": "no_polygon_proposal"
                    }
                  },
                  "polygon_proposal_changed": {
                    "value": {
                      "error": "polygon proposal changed: it is not the one reviewed; review it again",
                      "code": "polygon_proposal_changed"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/polygon-proposals/{code}/reject": {
      "post": {
        "operationId": "rejectPolygonProposal",
        "summary": "Reject a company's growing-area boundary proposal (platform)",
        "description": "SENS-A1 (#224): a platform admin rejects the boundary change waiting on a growing area of any company, with a reason the company reads in its activity log; the boundary in force stays. 409 when no proposal is waiting. Audited (`growing_area.polygon.reject`) in the area's company's activity log. Allowed for platform_admin only (never an OAuth client). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PolygonProposalRejection"
              },
              "example": {
                "reason": "The new boundary covers the neighbour's plot."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "What was rejected.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PolygonProposalRejected"
                },
                "example": {
                  "code": "VN-TGOR-0387",
                  "tenant": "coop-dl",
                  "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
                  "proposed_at": 1790007200.5,
                  "proposed_by": "admin@coop.example",
                  "reason": "The new boundary covers the neighbour's plot."
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing or too long reason, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: a string of 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the proposing company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No growing area has this code.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "No boundary proposal is waiting. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "no_polygon_proposal": {
                    "value": {
                      "error": "no polygon proposal: the area has no boundary change waiting for approval",
                      "code": "no_polygon_proposal"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/fruits/{code}": {
      "get": {
        "operationId": "getFruit",
        "summary": "One fruit record",
        "description": "A fruit of the caller's tenant by its code. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the fruits of its facilities' lots). The measurement fields come from the inspect envelopes bound to the fruit (knock, sensory override, scale); grade and eating window from the grading rules (see /v1/grading-rules).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Fruit code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "Q-014-0129"
          }
        ],
        "responses": {
          "200": {
            "description": "The fruit.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Fruit"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "Q-014-0129",
                  "n": 129,
                  "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                  "lot": "LO-260928-014",
                  "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "line": "A2",
                  "operator": "user-7",
                  "status": "recorded",
                  "labels_printed_at": 1790000000.5,
                  "created_at": 1790000000.5,
                  "updated_at": 1790560561.2,
                  "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                  "level": 3,
                  "level_pred": 3,
                  "maturity_class": "mature",
                  "confidence": 0.91,
                  "model": "sf100-m3",
                  "measured_at": 1790560560.0,
                  "weight_kg": 2.84,
                  "level_sensory": null,
                  "override": false,
                  "pending_review": false,
                  "grade": "A",
                  "eating_window": {
                    "start_days": 3,
                    "end_days": 4,
                    "from_date": "2026-10-01",
                    "to_date": "2026-10-02",
                    "band": "ambient",
                    "warning": null
                  },
                  "record_tier": "device_recorded",
                  "knock_envelope_id": "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30",
                  "scale_envelope_id": "6e3a1d9c-2b7f-4e8a-b5c4-9d0f1e2a3b47",
                  "override_envelope_id": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such fruit for this tenant: a fruit of another tenant, or of a lot outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: Q-014-0129",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/fruits/{code}/actions": {
      "post": {
        "operationId": "actOnFruit",
        "summary": "Operator action on a fruit: accept, re-measure, reject or sensory override",
        "description": "The operator console's actions on one fruit record (man1: sensory confirmation keys 1-4, accept into the lot, re-measure, reject). `accept` (recorded or overridden fruit) sets `accepted_at`, the status is unchanged; accepting again keeps the first time; it is 409 pending_review while the fruit's measurement is in review, and any later change of the bound measurement (a bind, a supersede, a review rejection) clears `accepted_at`. `override` (recorded or overridden) sets the sensory level and regrades with the tenant's grading rules: status overridden, effective level = the sensory level, record tier self_declared. `reject` (awaiting_device, recorded or overridden) sets status rejected and grade reject, which excludes the fruit from export counts. `remeasure` (recorded, overridden or rejected, or awaiting_device once the fruit was re-measured, so a refused round can be retried) moves the current measurement into the fruit's history (round n, replaced by round n + 1), returns the fruit to awaiting_device, and sends `set_session {lot, fruit, line[, operator], round}` again to the devices of the fruit's session while that session is open (otherwise each device is reported skipped, reason session_not_open); `round` is the new measurement_round as a string, which the device signs into the context of every later envelope. Envelopes of the superseded round never bind again: a `round` stamp other than the fruit's measurement_round is refused and an equal one binds, with no clock involved; an envelope without a stamp is quarantined for review (reason unverified_round) and binds only when the server received it after the re-measure and, when the same device has an accepted envelope in the superseded round, its event time is later than that one's (server and device clocks are never compared). Any other combination is 409 invalid transition; any action on a fruit whose lot is past open is 409 lot closed; any action on a fruit of a sampled lot (`POST /v1/lots/{lot}/samples`) is 409 lot sampled, since the sampling fixed the lot's export population; a closed session does not block an action. Idempotent per tenant and `idempotency_key`: replaying a key with the same fruit, type, level and reason returns 200 with the stored result and changes nothing (even if the fruit or lot changed since); the same key with anything else is 409. Only successful actions are stored. The reason is stored with the action and never returned or audited. Audited (`fruit.action`, replays included). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only the fruits of its facilities' lots); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "fruit_action"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Fruit code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "Q-014-0129"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FruitActionRequest"
              },
              "examples": {
                "accept": {
                  "value": {
                    "type": "accept",
                    "idempotency_key": "6f1c2a9e-4b7d-4e3a-9c8f-1d2e3f4a5b6c",
                    "client_ts": "2026-09-28T08:57:02+07:00"
                  }
                },
                "override": {
                  "value": {
                    "type": "override",
                    "level": 2,
                    "idempotency_key": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
                    "client_ts": "2026-09-28T08:57:02+07:00"
                  }
                },
                "reject": {
                  "value": {
                    "type": "reject",
                    "reason": "cracked husk",
                    "idempotency_key": "9c8b7a6f-5e4d-4c3b-8a29-1f0e9d8c7b6a",
                    "client_ts": "2026-09-28T08:57:02+07:00"
                  }
                },
                "remeasure": {
                  "value": {
                    "type": "remeasure",
                    "idempotency_key": "2b3c4d5e-6f70-4a81-9b2c-3d4e5f607182",
                    "client_ts": "2026-09-28T08:57:02+07:00"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The action applied, or the stored result of an earlier request with the same key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FruitActionResult"
                },
                "examples": {
                  "accept": {
                    "value": {
                      "action": {
                        "id": 41,
                        "type": "accept",
                        "level": null,
                        "client_ts": "2026-09-28T08:57:02+07:00",
                        "created_at": 1790560600.0
                      },
                      "fruit": {
                        "tenant": "coop-dl",
                        "code": "Q-014-0129",
                        "n": 129,
                        "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                        "lot": "LO-260928-014",
                        "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                        "line": "A2",
                        "operator": "user-7",
                        "status": "recorded",
                        "labels_printed_at": 1790000000.5,
                        "created_at": 1790000000.5,
                        "updated_at": 1790560600.0,
                        "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                        "level": 3,
                        "level_pred": 3,
                        "maturity_class": "mature",
                        "confidence": 0.91,
                        "model": "sf100-m3",
                        "measured_at": 1790560560.0,
                        "weight_kg": 2.84,
                        "level_sensory": null,
                        "override": false,
                        "pending_review": false,
                        "grade": "A",
                        "eating_window": {
                          "start_days": 3,
                          "end_days": 4,
                          "from_date": "2026-10-01",
                          "to_date": "2026-10-02",
                          "band": "ambient",
                          "warning": null
                        },
                        "record_tier": "device_recorded",
                        "knock_envelope_id": "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30",
                        "scale_envelope_id": "6e3a1d9c-2b7f-4e8a-b5c4-9d0f1e2a3b47",
                        "override_envelope_id": null
                      },
                      "accepted_at": 1790560600.0,
                      "measurement_round": 0,
                      "commands": []
                    }
                  },
                  "override": {
                    "value": {
                      "action": {
                        "id": 41,
                        "type": "override",
                        "level": 2,
                        "client_ts": "2026-09-28T08:57:02+07:00",
                        "created_at": 1790560600.0
                      },
                      "fruit": {
                        "tenant": "coop-dl",
                        "code": "Q-014-0129",
                        "n": 129,
                        "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                        "lot": "LO-260928-014",
                        "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                        "line": "A2",
                        "operator": "user-7",
                        "status": "overridden",
                        "labels_printed_at": 1790000000.5,
                        "created_at": 1790000000.5,
                        "updated_at": 1790560600.0,
                        "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                        "level": 2,
                        "level_pred": 3,
                        "maturity_class": "mature",
                        "confidence": 0.91,
                        "model": "sf100-m3",
                        "measured_at": 1790560560.0,
                        "weight_kg": 2.84,
                        "level_sensory": 2,
                        "override": true,
                        "pending_review": false,
                        "grade": "B",
                        "eating_window": {
                          "start_days": 4,
                          "end_days": 6,
                          "from_date": "2026-10-02",
                          "to_date": "2026-10-04",
                          "band": "ambient",
                          "warning": null
                        },
                        "record_tier": "self_declared",
                        "knock_envelope_id": "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30",
                        "scale_envelope_id": "6e3a1d9c-2b7f-4e8a-b5c4-9d0f1e2a3b47",
                        "override_envelope_id": null
                      },
                      "accepted_at": null,
                      "measurement_round": 0,
                      "commands": []
                    }
                  },
                  "reject": {
                    "value": {
                      "action": {
                        "id": 41,
                        "type": "reject",
                        "level": null,
                        "client_ts": "2026-09-28T08:57:02+07:00",
                        "created_at": 1790560600.0
                      },
                      "fruit": {
                        "tenant": "coop-dl",
                        "code": "Q-014-0129",
                        "n": 129,
                        "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                        "lot": "LO-260928-014",
                        "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                        "line": "A2",
                        "operator": "user-7",
                        "status": "rejected",
                        "labels_printed_at": 1790000000.5,
                        "created_at": 1790000000.5,
                        "updated_at": 1790560600.0,
                        "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                        "level": 3,
                        "level_pred": 3,
                        "maturity_class": "mature",
                        "confidence": 0.91,
                        "model": "sf100-m3",
                        "measured_at": 1790560560.0,
                        "weight_kg": 2.84,
                        "level_sensory": null,
                        "override": false,
                        "pending_review": false,
                        "grade": "reject",
                        "eating_window": {
                          "start_days": 3,
                          "end_days": 4,
                          "from_date": "2026-10-01",
                          "to_date": "2026-10-02",
                          "band": "ambient",
                          "warning": null
                        },
                        "record_tier": "self_declared",
                        "knock_envelope_id": "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30",
                        "scale_envelope_id": "6e3a1d9c-2b7f-4e8a-b5c4-9d0f1e2a3b47",
                        "override_envelope_id": null
                      },
                      "accepted_at": null,
                      "measurement_round": 0,
                      "commands": []
                    }
                  },
                  "remeasure": {
                    "value": {
                      "action": {
                        "id": 41,
                        "type": "remeasure",
                        "level": null,
                        "client_ts": "2026-09-28T08:57:02+07:00",
                        "created_at": 1790560600.0
                      },
                      "fruit": {
                        "tenant": "coop-dl",
                        "code": "Q-014-0129",
                        "n": 129,
                        "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                        "lot": "LO-260928-014",
                        "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                        "line": "A2",
                        "operator": "user-7",
                        "status": "awaiting_device",
                        "labels_printed_at": 1790000000.5,
                        "created_at": 1790000000.5,
                        "updated_at": 1790560600.0,
                        "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                        "level": null,
                        "level_pred": null,
                        "maturity_class": null,
                        "confidence": null,
                        "model": null,
                        "measured_at": null,
                        "weight_kg": null,
                        "level_sensory": null,
                        "override": false,
                        "pending_review": false,
                        "grade": null,
                        "eating_window": null,
                        "record_tier": null,
                        "knock_envelope_id": null,
                        "scale_envelope_id": null,
                        "override_envelope_id": null
                      },
                      "accepted_at": null,
                      "measurement_round": 1,
                      "commands": [
                        {
                          "device_id": "knk-1",
                          "command_id": "9d2e7f40-1c3b-4a5e-8f6d-0b7c2a9e4d18",
                          "status": "sent",
                          "reason": null
                        },
                        {
                          "device_id": "scale-1",
                          "command_id": "1a6b3c8d-2e4f-4a7b-9c0d-5e8f1a2b3c4d",
                          "status": "sent",
                          "reason": null
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not an object, an unknown field, a bad type, level, reason, idempotency_key or client_ts, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "not_an_object": {
                    "value": {
                      "error": "expected a JSON object",
                      "code": "expected_a_json_object"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "type": {
                    "value": {
                      "error": "invalid type: one of accept, remeasure, reject, override",
                      "code": "invalid_type"
                    }
                  },
                  "level": {
                    "value": {
                      "error": "invalid level: an integer from 1 to 4",
                      "code": "invalid_level"
                    }
                  },
                  "level_not_allowed": {
                    "value": {
                      "error": "invalid level: only an override takes a level",
                      "code": "invalid_level"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: a string of 1 to 200 characters, or null",
                      "code": "invalid_reason"
                    }
                  },
                  "idempotency_key": {
                    "value": {
                      "error": "invalid idempotency_key: 16 to 64 letters, digits, '-' or '_'",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "client_ts": {
                    "value": {
                      "error": "invalid client_ts: an ISO 8601 date-time with a zone offset",
                      "code": "invalid_client_ts"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such fruit for this tenant: a fruit of another tenant, or of a lot outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: Q-014-0129",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The fruit's lot is past open or was sampled, the action does not apply to the fruit's state, an accept while the fruit's measurement is in review, or the idempotency key was already used for another request. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_closed": {
                    "value": {
                      "error": "lot closed: lot is closed",
                      "code": "lot_closed"
                    }
                  },
                  "invalid_transition": {
                    "value": {
                      "error": "invalid transition: awaiting_device to accept",
                      "code": "invalid_transition"
                    }
                  },
                  "pending_review": {
                    "value": {
                      "error": "pending review: the fruit's measurement is in review",
                      "code": "pending_review"
                    }
                  },
                  "key_reused": {
                    "value": {
                      "error": "idempotency key reused",
                      "code": "idempotency_key_reused"
                    }
                  },
                  "lot_sampled": {
                    "value": {
                      "error": "lot sampled: its export population is final",
                      "code": "lot_sampled"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/fsma.csv": {
      "get": {
        "operationId": "getFsmaCsv",
        "summary": "FSMA 204 sortable spreadsheet for a time range",
        "description": "Rows for the caller's tenant with `start <= event time < end`. Both bounds are optional. A value that is not an ISO 8601 date-time answers 400. Each row is a critical tracking event of the caller's tenant (device events, departures and lot merges; see FsmaRow) with the FSMA 204 key data elements (#158).",
        "x-sdk-description": "Rows for the caller's tenant with `start <= event time < end`. Both bounds are optional. A value that is not an ISO 8601 date-time answers 400.",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "trace_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "start",
            "in": "query",
            "required": false,
            "description": "Inclusive lower bound, ISO 8601 date-time.",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "example": "2026-09-01T00:00:00+07:00"
          },
          {
            "name": "end",
            "in": "query",
            "required": false,
            "description": "Exclusive upper bound, ISO 8601 date-time.",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "example": "2026-10-01T00:00:00+07:00"
          }
        ],
        "responses": {
          "200": {
            "description": "CSV with a header row, then one row per critical tracking event sorted by time; the columns are the FsmaRow schema's, in its order. The same columns as the per-lot export. A text cell starting with =, +, -, @, a tab or a carriage return gets a leading ' so a spreadsheet never runs it as a formula.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "traceability_lot_code,critical_tracking_event,event_date,event_time,location,quantity,unit_of_measure,growing_area,parcel,producer,device_id,event_id,commodity,variety,field_name,traceability_lot_code_source,traceability_lot_code_source_reference,shipper_location_name,shipper_location_address,shipper_location_gln,recipient_location_name,recipient_location_address,recipient_location_gln,reference_document_type,reference_document_number,container,input_traceability_lot_code,input_quantity\r\n",
                "x-sdk-example": "traceability_lot_code,critical_tracking_event,event_date,event_time,location,quantity,unit_of_measure,growing_area,parcel,producer,device_id,event_id\r\n"
              }
            },
            "x-sdk-description": "CSV with a header row (same columns as the per-lot export)."
          },
          "400": {
            "description": "start or end is not a valid ISO 8601 date-time, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_date": {
                    "value": {
                      "error": "Invalid isoformat string: 'yesterday'",
                      "code": "invalid_isoformat_string"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways": {
      "get": {
        "operationId": "listGateways",
        "summary": "Gateways of the caller's tenant",
        "description": "Gateways ordered by id, with keyset pagination (at most 100 per page). Allowed for platform_admin, tenant_admin and auditor; gateways are site-wide, so operators are refused.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of gateways.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6Imtuay0xIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of gateways.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GatewayPage"
                },
                "example": {
                  "items": [
                    {
                      "gateway_id": "gw-01",
                      "tenant": "coop-dl",
                      "site": "ph1",
                      "facility": "VN-TGPH-021",
                      "display_name": "Packing hall gateway",
                      "status": "active",
                      "approval": "approved",
                      "approval_reason": null,
                      "approval_at": 1790000100.0
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createGateway",
        "summary": "Register a gateway",
        "description": "Registers an active gateway of the caller's tenant. The id must be unused by every tenant's gateways and devices: an existing record is never replaced. Audited (`gateway.create`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GatewayCreate"
              },
              "example": {
                "gateway_id": "gw-01",
                "site": "ph1",
                "facility": "VN-TGPH-021",
                "display_name": "Packing hall gateway"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new gateway.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Gateway"
                },
                "example": {
                  "gateway_id": "gw-01",
                  "tenant": "coop-dl",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "display_name": "Packing hall gateway",
                  "status": "active",
                  "approval": "approved",
                  "approval_reason": null,
                  "approval_at": 1790000100.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a malformed id or site, a facility that is not one of the caller's tenant, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_gateway_id": {
                    "value": {
                      "error": "invalid gateway_id: 1 to 64 letters, digits, '.', '_' or '-', starting with a letter or digit",
                      "code": "invalid_gateway_id"
                    }
                  },
                  "unknown_facility": {
                    "value": {
                      "error": "unknown facility",
                      "code": "unknown_facility"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The id is used by a gateway or device (of any tenant; the owner is not revealed). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded). SELF-2-8 (#197): or the facility is a company's proposal CropPath has not approved yet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "gateway_id_taken": {
                    "value": {
                      "error": "gateway id taken",
                      "code": "gateway_id_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  },
                  "facility_not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/heartbeat": {
      "get": {
        "operationId": "getGatewayHeartbeat",
        "summary": "A gateway's newest status heartbeat",
        "description": "#24: the newest status heartbeat of a gateway of the caller's tenant. A gateway signs a `status` envelope about itself every 30 s by default (profile `vn.agritrace.gateway`, /developers/downloads/profiles/gateway.json: its gateway id as `device.id`, on the ingest route `{tenant}/{site}/{gateway id}/status`); the server keeps the newest one of each gateway, never as an envelope: ordered by `seq`, but a signed heartbeat with a lower `seq` and a later time is kept (a reset gateway) and a signed one with a higher `seq` and an earlier time is superseded; one dated past the server's maximum future skew is rejected (400 `future_timestamp`). `heartbeat` is null until the gateway sent one. A value the heartbeat did not carry is null. Same roles as listing the gateways; a gateway of another tenant answers exactly like a missing one. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Gateway id.",
            "schema": {
              "type": "string"
            },
            "example": "gw-01"
          }
        ],
        "responses": {
          "200": {
            "description": "The gateway's newest heartbeat, or null.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GatewayHeartbeatStatus"
                },
                "example": {
                  "gateway_id": "gw-01",
                  "heartbeat": {
                    "received_at": 1790100030.25,
                    "time": "2026-09-23T08:00:30.000+00:00",
                    "seq": 2881,
                    "signed": true,
                    "outbox_depth": 3,
                    "dead_letter_count": 0,
                    "link": {
                      "state": "connected"
                    },
                    "peripherals_ready": [
                      {
                        "device": "knk-1",
                        "ready": true
                      },
                      {
                        "device": "scale-1",
                        "ready": false
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway for this tenant: a gateway of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: gw-01",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/status-series": {
      "get": {
        "operationId": "getGatewayStatusSeries",
        "summary": "A gateway's status time series",
        "description": "#128: the status series of a gateway of the caller's tenant. The server stores at most one of the gateway's status heartbeats a minute (the first one it keeps in each UTC minute of reception) and adds it to the gateway's hourly rollup. `grain=minute` returns those samples; `hourly` (the default) the hourly rollups; `daily` the hourly rollups merged per UTC day. A rollup gives the number of samples, for the outbox depth, the dead-letter count and the devices listed and ready the minimum, maximum, mean (null when no sample carried the value) and count of the samples that carried it, and the samples per link state. Samples are kept 30 days and hourly rollups 2 years; the range is clipped to what is kept (`from` in the answer is the start actually read, aligned down to the grain) and is at most 1 day for `minute`, 31 days for `hourly` and 731 days for `daily` (`range_too_long`). The newest heartbeat itself is `getGatewayHeartbeat`. Same roles as listing the gateways; a gateway of another tenant answers exactly like a missing one. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Gateway id.",
            "schema": {
              "type": "string"
            },
            "example": "gw-01"
          },
          {
            "name": "grain",
            "in": "query",
            "required": false,
            "description": "A sample a minute, or the hourly or daily rollups.",
            "schema": {
              "type": "string",
              "enum": [
                "minute",
                "hourly",
                "daily"
              ],
              "default": "hourly"
            },
            "example": "hourly"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Start: an ISO 8601 date or date-time (+07:00 without an offset). Default: 1 day (minute), 7 days (hourly) or 365 days (daily) before `to`.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-01T00:00:00+07:00"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "End (excluded), as `from`. Default: now.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-02T00:00:00+07:00"
          }
        ],
        "responses": {
          "200": {
            "description": "The series, oldest first.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GatewayStatusSeries"
                },
                "example": {
                  "gateway_id": "gw-01",
                  "grain": "hourly",
                  "bucket_s": 3600.0,
                  "from": 1790100000.0,
                  "to": 1790107200.0,
                  "items": [
                    {
                      "bucket_start": 1790100000.0,
                      "samples": 60,
                      "outbox_depth": {
                        "min": 0,
                        "max": 12,
                        "mean": 2.5,
                        "count": 60
                      },
                      "dead_letter_count": {
                        "min": 0,
                        "max": 0,
                        "mean": 0.0,
                        "count": 60
                      },
                      "peripherals_ready": {
                        "min": 1,
                        "max": 2,
                        "mean": 1.9,
                        "count": 60
                      },
                      "peripherals_total": {
                        "min": 2,
                        "max": 2,
                        "mean": 2.0,
                        "count": 60
                      },
                      "link": {
                        "connected": 58,
                        "disconnected": 2,
                        "unknown": 0
                      }
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A bad grain or time, a range whose start is not before its end or longer than the grain allows, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_grain": {
                    "value": {
                      "error": "bad grain: minute, hourly or daily",
                      "code": "bad_grain"
                    }
                  },
                  "bad_from": {
                    "value": {
                      "error": "bad from",
                      "code": "bad_from"
                    }
                  },
                  "bad_to": {
                    "value": {
                      "error": "bad to",
                      "code": "bad_to"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range: from must be before to",
                      "code": "bad_range"
                    }
                  },
                  "range_too_long": {
                    "value": {
                      "error": "range too long",
                      "code": "range_too_long"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway for this tenant: a gateway of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: gw-01",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/grading-rules": {
      "get": {
        "operationId": "listGradingRules",
        "summary": "Grading rules of the caller's tenant",
        "description": "The tenant's grading rules, one per variety, by variety with keyset pagination. A variety without rules (and a lot without a variety) is graded with the platform default (see GradingRules). Allowed for platform_admin, tenant_admin and auditor; operators and lab are refused. Each page also carries `platform_default`, the rules in force for a variety without its own.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "grading_rule_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJ2YXJpZXR5IjoiUmk2In0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of grading rules.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GradingRulePage"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "tenant": "coop-dl",
                      "variety": "Ri6",
                      "rules": {
                        "a_levels": [
                          2,
                          3
                        ],
                        "reject_levels": [
                          1,
                          4
                        ],
                        "a_weight_kg": [
                          [
                            2.0,
                            5.0
                          ]
                        ],
                        "a_min_confidence": 0.8,
                        "eating_window": [
                          {
                            "band": "ambient",
                            "end_days": 7,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": "immature"
                          },
                          {
                            "band": "ambient",
                            "end_days": 6,
                            "level": 2,
                            "max_days": 1,
                            "min_days": 0,
                            "start_days": 4,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 4,
                            "level": 2,
                            "max_days": 3,
                            "min_days": 2,
                            "start_days": 3,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 2,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 4,
                            "start_days": 1,
                            "warning": "eat_soon"
                          },
                          {
                            "band": "ambient",
                            "end_days": 4,
                            "level": 3,
                            "max_days": 1,
                            "min_days": 0,
                            "start_days": 3,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 3,
                            "level": 3,
                            "max_days": 3,
                            "min_days": 2,
                            "start_days": 2,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 1,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 4,
                            "start_days": 0,
                            "warning": "eat_soon"
                          },
                          {
                            "band": "ambient",
                            "end_days": 1,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          },
                          {
                            "band": "14-18C",
                            "end_days": 10,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 7,
                            "warning": "immature"
                          },
                          {
                            "band": "14-18C",
                            "end_days": 8,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": null
                          },
                          {
                            "band": "14-18C",
                            "end_days": 6,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 4,
                            "warning": null
                          },
                          {
                            "band": "14-18C",
                            "end_days": 2,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          },
                          {
                            "band": "10-13C",
                            "end_days": 12,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 9,
                            "warning": "immature"
                          },
                          {
                            "band": "10-13C",
                            "end_days": 10,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 7,
                            "warning": null
                          },
                          {
                            "band": "10-13C",
                            "end_days": 8,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": null
                          },
                          {
                            "band": "10-13C",
                            "end_days": 2,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          }
                        ]
                      },
                      "updated_at": 1790000000.5,
                      "updated_by": "admin@coop.example"
                    }
                  ],
                  "next_cursor": null,
                  "platform_default": {
                    "a_levels": [
                      2,
                      3
                    ],
                    "reject_levels": [
                      1,
                      4
                    ],
                    "a_weight_kg": [
                      [
                        2.0,
                        5.0
                      ]
                    ],
                    "a_min_confidence": 0.8,
                    "eating_window": [
                      {
                        "band": "ambient",
                        "end_days": 7,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": "immature"
                      },
                      {
                        "band": "ambient",
                        "end_days": 6,
                        "level": 2,
                        "max_days": 1,
                        "min_days": 0,
                        "start_days": 4,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 4,
                        "level": 2,
                        "max_days": 3,
                        "min_days": 2,
                        "start_days": 3,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 2,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 4,
                        "start_days": 1,
                        "warning": "eat_soon"
                      },
                      {
                        "band": "ambient",
                        "end_days": 4,
                        "level": 3,
                        "max_days": 1,
                        "min_days": 0,
                        "start_days": 3,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 3,
                        "level": 3,
                        "max_days": 3,
                        "min_days": 2,
                        "start_days": 2,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 1,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 4,
                        "start_days": 0,
                        "warning": "eat_soon"
                      },
                      {
                        "band": "ambient",
                        "end_days": 1,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      },
                      {
                        "band": "14-18C",
                        "end_days": 10,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 7,
                        "warning": "immature"
                      },
                      {
                        "band": "14-18C",
                        "end_days": 8,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": null
                      },
                      {
                        "band": "14-18C",
                        "end_days": 6,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 4,
                        "warning": null
                      },
                      {
                        "band": "14-18C",
                        "end_days": 2,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      },
                      {
                        "band": "10-13C",
                        "end_days": 12,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 9,
                        "warning": "immature"
                      },
                      {
                        "band": "10-13C",
                        "end_days": 10,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 7,
                        "warning": null
                      },
                      {
                        "band": "10-13C",
                        "end_days": 8,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": null
                      },
                      {
                        "band": "10-13C",
                        "end_days": 2,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "A cursor this API did not issue, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/grading-rules/{variety}": {
      "put": {
        "operationId": "putGradingRules",
        "summary": "Create or replace the grading rules of a variety",
        "description": "Validates and stores the rules of one variety of the caller's tenant (create or replace), and records the version it wrote in the variety's history (GET /v1/grading-rules/{variety}/history) in the same transaction. Fruits are not regraded by this call: each fruit is regraded when a measurement is next bound to it or reviewed. Audited (`grading_rule.update`, entity id = the rule's server id, `after` = the eating-window row count; the variety is never recorded). Allowed for platform_admin and tenant_admin; auditor, operator and lab are refused. Second admin approval (INTEGRITY-3, #203): while the company requires a second admin (PUT /v1/company/four-eyes), a direct call answers 403 `second_admin_approval_required` before anything is done (no audit row, no Idempotency-Key used): ask for it with POST /v1/approval-requests, and another admin of the company approves it.",
        "x-sdk-description": "Validates and stores the rules of one variety of the caller's tenant (create or replace), and records the version it wrote in the variety's history (GET /v1/grading-rules/{variety}/history) in the same transaction. Fruits are not regraded by this call: each fruit is regraded when a measurement is next bound to it or reviewed. Audited (`grading_rule.update`, entity id = the rule's server id, `after` = the eating-window row count; the variety is never recorded). Allowed for platform_admin and tenant_admin; auditor, operator and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "grading_rule_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "variety",
            "in": "path",
            "required": true,
            "description": "Lot variety (1 to 64 characters), as on the lot.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "Ri6"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GradingRules"
              },
              "example": {
                "a_levels": [
                  2,
                  3
                ],
                "reject_levels": [
                  1,
                  4
                ],
                "a_weight_kg": [
                  [
                    2.0,
                    5.0
                  ]
                ],
                "a_min_confidence": 0.8,
                "eating_window": [
                  {
                    "band": "ambient",
                    "end_days": 7,
                    "level": 1,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 5,
                    "warning": "immature"
                  },
                  {
                    "band": "ambient",
                    "end_days": 6,
                    "level": 2,
                    "max_days": 1,
                    "min_days": 0,
                    "start_days": 4,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 4,
                    "level": 2,
                    "max_days": 3,
                    "min_days": 2,
                    "start_days": 3,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 2,
                    "level": 2,
                    "max_days": 30,
                    "min_days": 4,
                    "start_days": 1,
                    "warning": "eat_soon"
                  },
                  {
                    "band": "ambient",
                    "end_days": 4,
                    "level": 3,
                    "max_days": 1,
                    "min_days": 0,
                    "start_days": 3,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 3,
                    "level": 3,
                    "max_days": 3,
                    "min_days": 2,
                    "start_days": 2,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 1,
                    "level": 3,
                    "max_days": 30,
                    "min_days": 4,
                    "start_days": 0,
                    "warning": "eat_soon"
                  },
                  {
                    "band": "ambient",
                    "end_days": 1,
                    "level": 4,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 0,
                    "warning": "overripe"
                  },
                  {
                    "band": "14-18C",
                    "end_days": 10,
                    "level": 1,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 7,
                    "warning": "immature"
                  },
                  {
                    "band": "14-18C",
                    "end_days": 8,
                    "level": 2,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 5,
                    "warning": null
                  },
                  {
                    "band": "14-18C",
                    "end_days": 6,
                    "level": 3,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 4,
                    "warning": null
                  },
                  {
                    "band": "14-18C",
                    "end_days": 2,
                    "level": 4,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 0,
                    "warning": "overripe"
                  },
                  {
                    "band": "10-13C",
                    "end_days": 12,
                    "level": 1,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 9,
                    "warning": "immature"
                  },
                  {
                    "band": "10-13C",
                    "end_days": 10,
                    "level": 2,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 7,
                    "warning": null
                  },
                  {
                    "band": "10-13C",
                    "end_days": 8,
                    "level": 3,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 5,
                    "warning": null
                  },
                  {
                    "band": "10-13C",
                    "end_days": 2,
                    "level": 4,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 0,
                    "warning": "overripe"
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The stored rules.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GradingRule"
                },
                "example": {
                  "id": 3,
                  "tenant": "coop-dl",
                  "variety": "Ri6",
                  "rules": {
                    "a_levels": [
                      2,
                      3
                    ],
                    "reject_levels": [
                      1,
                      4
                    ],
                    "a_weight_kg": [
                      [
                        2.0,
                        5.0
                      ]
                    ],
                    "a_min_confidence": 0.8,
                    "eating_window": [
                      {
                        "band": "ambient",
                        "end_days": 7,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": "immature"
                      },
                      {
                        "band": "ambient",
                        "end_days": 6,
                        "level": 2,
                        "max_days": 1,
                        "min_days": 0,
                        "start_days": 4,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 4,
                        "level": 2,
                        "max_days": 3,
                        "min_days": 2,
                        "start_days": 3,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 2,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 4,
                        "start_days": 1,
                        "warning": "eat_soon"
                      },
                      {
                        "band": "ambient",
                        "end_days": 4,
                        "level": 3,
                        "max_days": 1,
                        "min_days": 0,
                        "start_days": 3,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 3,
                        "level": 3,
                        "max_days": 3,
                        "min_days": 2,
                        "start_days": 2,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 1,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 4,
                        "start_days": 0,
                        "warning": "eat_soon"
                      },
                      {
                        "band": "ambient",
                        "end_days": 1,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      },
                      {
                        "band": "14-18C",
                        "end_days": 10,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 7,
                        "warning": "immature"
                      },
                      {
                        "band": "14-18C",
                        "end_days": 8,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": null
                      },
                      {
                        "band": "14-18C",
                        "end_days": 6,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 4,
                        "warning": null
                      },
                      {
                        "band": "14-18C",
                        "end_days": 2,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      },
                      {
                        "band": "10-13C",
                        "end_days": 12,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 9,
                        "warning": "immature"
                      },
                      {
                        "band": "10-13C",
                        "end_days": 10,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 7,
                        "warning": null
                      },
                      {
                        "band": "10-13C",
                        "end_days": 8,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": null
                      },
                      {
                        "band": "10-13C",
                        "end_days": 2,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      }
                    ]
                  },
                  "updated_at": 1790000000.5,
                  "updated_by": "admin@coop.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not an object, invalid rules, a bad variety, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "not_an_object": {
                    "value": {
                      "error": "expected a JSON object",
                      "code": "expected_a_json_object"
                    }
                  },
                  "invalid_rules": {
                    "value": {
                      "error": "invalid rules: a_weight_kg bands must not overlap",
                      "code": "invalid_rules"
                    }
                  },
                  "invalid_variety": {
                    "value": {
                      "error": "invalid variety: a string of 1 to 64 characters",
                      "code": "invalid_variety"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growers": {
      "get": {
        "operationId": "listGrowers",
        "summary": "Growers of the caller's tenant",
        "description": "Newest first with keyset pagination. The name appears for tenant_admin and platform_admin (who manage growers) and, for auditors and operators, only when public_consent is on; display_name is `Co-op member #<id>` without consent. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of growers.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6MTJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of growers.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowerPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 12,
                      "tenant": "coop-dl",
                      "display_name": "Co-op member #12",
                      "cooperative": "HTX Ngu Hiep",
                      "public_consent": false,
                      "consent_at": null,
                      "consent_date": null,
                      "consent_scope": null,
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createGrower",
        "summary": "Register a grower",
        "description": "Creates a grower of the caller's tenant. Audited (`grower.create`; the id and consent flag only, never the name). Allowed for platform_admin and tenant_admin. #163: a grower created with public_consent on also gets its first consent record (channel `record_edit`, listGrowerConsents). Such a grant carries no evidence, so staff see it as \"no evidence recorded\" (`in_force[].evidence_recorded` false); granting through public_consent is kept for SDK 0.2.0 and is to be deprecated in favour of recordGrowerConsent, which needs written evidence (turning it off, a withdrawal, stays).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowerCreate"
              },
              "example": {
                "name": "Nguyen Van An",
                "cooperative": "HTX Ngu Hiep",
                "public_consent": false
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new grower.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Grower"
                },
                "example": {
                  "id": 12,
                  "tenant": "coop-dl",
                  "display_name": "Co-op member #12",
                  "cooperative": "HTX Ngu Hiep",
                  "public_consent": false,
                  "consent_at": null,
                  "consent_date": null,
                  "consent_scope": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "name": "Nguyen Van An"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing name, a non-boolean consent, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_name": {
                    "value": {
                      "error": "invalid name: a string of at most 200 characters, not empty",
                      "code": "invalid_name"
                    }
                  },
                  "invalid_public_consent": {
                    "value": {
                      "error": "invalid public_consent: a boolean",
                      "code": "invalid_public_consent"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The caller's tenant is not registered. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant_not_registered": {
                    "value": {
                      "error": "tenant not registered",
                      "code": "tenant_not_registered"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Creates a grower of the caller's tenant. Audited (`grower.create`; the id and consent flag only, never the name). Allowed for platform_admin and tenant_admin."
      }
    },
    "/v1/growers/{id}": {
      "get": {
        "operationId": "getGrower",
        "summary": "One grower",
        "description": "The name appears for tenant_admin and platform_admin (who manage growers) and, for auditors and operators, only when public_consent is on; display_name is `Co-op member #<id>` without consent. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Grower id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          }
        ],
        "responses": {
          "200": {
            "description": "The grower as the caller may see it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Grower"
                },
                "example": {
                  "id": 12,
                  "tenant": "coop-dl",
                  "display_name": "Co-op member #12",
                  "cooperative": "HTX Ngu Hiep",
                  "public_consent": false,
                  "consent_at": null,
                  "consent_date": null,
                  "consent_scope": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such grower in this tenant (a grower of another tenant, or an id that is not a positive integer, answers exactly like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateGrower",
        "summary": "Edit a grower or its consent",
        "description": "Changes name, cooperative or public_consent. Turning consent on records consent_at; turning it off clears it. Audited (`grower.update`; field names and the consent flag only). #163: a change of public_consent is also appended to the grower's consent records (channel `record_edit`, listGrowerConsents). Such a grant carries no evidence, so staff see it as \"no evidence recorded\" (`in_force[].evidence_recorded` false); granting through public_consent is kept for SDK 0.2.0 and is to be deprecated in favour of recordGrowerConsent, which needs written evidence (turning it off, a withdrawal, stays).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Grower id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowerUpdate"
              },
              "example": {
                "public_consent": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The grower after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Grower"
                },
                "example": {
                  "id": 12,
                  "tenant": "coop-dl",
                  "display_name": "Nguyen Van An",
                  "cooperative": "HTX Ngu Hiep",
                  "public_consent": true,
                  "consent_at": 1790000100.0,
                  "consent_date": null,
                  "consent_scope": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "name": "Nguyen Van An"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an empty body, a field that cannot be changed, a value out of bounds, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "nothing_to_update": {
                    "value": {
                      "error": "nothing to update",
                      "code": "nothing_to_update"
                    }
                  },
                  "field_not_editable": {
                    "value": {
                      "error": "field not editable",
                      "code": "field_not_editable"
                    }
                  },
                  "invalid_public_consent": {
                    "value": {
                      "error": "invalid public_consent: a boolean",
                      "code": "invalid_public_consent"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such grower in this tenant (a grower of another tenant, or an id that is not a positive integer, answers exactly like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Changes name, cooperative or public_consent. Turning consent on records consent_at; turning it off clears it. Audited (`grower.update`; field names and the consent flag only)."
      }
    },
    "/v1/growing-areas": {
      "get": {
        "operationId": "listGrowingAreas",
        "summary": "Growing areas the caller's tenant may read",
        "description": "The tenant's own areas and the unowned (seeded) ones, ordered by code, with keyset pagination. The grower's name appears only for the owning admins or with public consent; the polygon only for the owning tenant_admin and platform_admin. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of growing areas.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IlZOLVRHT1ItMDM4NyJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "admin_units",
            "in": "query",
            "required": false,
            "description": "#273: `1` adds the address by official code (`province_code`, `commune_code`, `admin_units_version`, `address_status`, `address_before_reform`, `address_candidates`); `0` or none leaves them out and answers exactly as before; any other value is refused (400 `bad admin_units`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "One page of growing areas.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingAreaPage"
                },
                "example": {
                  "items": [
                    {
                      "code": "VN-DL-SR-0123",
                      "tenant": null,
                      "name": null,
                      "crop": "durian",
                      "variety": null,
                      "province": null,
                      "district": null,
                      "commune": null,
                      "area_ha": 1.0,
                      "yield_kg_per_ha": 20000.0,
                      "trees": null,
                      "planted_year": null,
                      "grower_id": null,
                      "gacc_puc_code": null,
                      "source": "seed",
                      "approved_at": null,
                      "created_at": null,
                      "updated_at": null,
                      "registry_changed_at": null,
                      "cap_kg": 20000.0,
                      "approval_current": false,
                      "grower": null
                    },
                    {
                      "code": "VN-TGOR-0387",
                      "tenant": "coop-dl",
                      "name": "Orchard 387",
                      "crop": "durian",
                      "variety": "Ri6",
                      "province": "Tien Giang",
                      "district": "Cai Lay",
                      "commune": "Ngu Hiep",
                      "area_ha": 2.0,
                      "yield_kg_per_ha": 10000.0,
                      "trees": 240,
                      "planted_year": 2015,
                      "grower_id": 12,
                      "gacc_puc_code": "VNPUC-TG-0387",
                      "source": "manual",
                      "approved_at": null,
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5,
                      "registry_changed_at": null,
                      "cap_kg": 20000.0,
                      "approval_current": false,
                      "grower": {
                        "id": 12,
                        "tenant": "coop-dl",
                        "display_name": "Co-op member #12",
                        "cooperative": "HTX Ngu Hiep",
                        "public_consent": false,
                        "consent_at": null,
                        "consent_date": null,
                        "consent_scope": null,
                        "created_at": 1790000000.5,
                        "updated_at": 1790000000.5
                      }
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, `admin_units` not 0 or 1, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_admin_units": {
                    "value": {
                      "error": "bad admin_units",
                      "code": "bad_admin_units"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "bad_cursor": {
                      "value": {
                        "error": "bad cursor",
                        "code": "bad_cursor"
                      }
                    },
                    "bad_limit": {
                      "value": {
                        "error": "bad limit",
                        "code": "bad_limit"
                      }
                    },
                    "bad_request_id": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createGrowingArea",
        "summary": "Register a growing area",
        "description": "Creates an unapproved area (source `manual`) owned by the tenant the caller acts for; the body cannot name another tenant. The code is the key across all tenants: a taken code is 409 whoever owns it. Audited (`growing_area.create`). Allowed for platform_admin and tenant_admin. #273: the address in Viet Nam is given by official code, `province_code` and `commune_code` from `getAdminUnits`; the server writes the official names (`district` null). The text fields `province`, `district` and `commune` are deprecated (sunset 1 May 2027): a text-only address is still accepted, stores the record as not yet coded and answers with the `Deprecation`, `Sunset` and `Link` headers.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowingAreaCreate"
              },
              "example": {
                "code": "VN-TGOR-0387",
                "area_ha": 2,
                "yield_kg_per_ha": 10000,
                "name": "Orchard 387",
                "crop": "durian",
                "variety": "Ri6",
                "province_code": "82",
                "commune_code": "28516",
                "trees": 240,
                "planted_year": 2015,
                "grower_id": 12,
                "gacc_puc_code": "VNPUC-TG-0387",
                "polygon": {
                  "type": "Polygon",
                  "coordinates": [
                    [
                      [
                        106.1,
                        10.4
                      ],
                      [
                        106.2,
                        10.4
                      ],
                      [
                        106.2,
                        10.5
                      ],
                      [
                        106.1,
                        10.5
                      ],
                      [
                        106.1,
                        10.4
                      ]
                    ]
                  ]
                }
              },
              "x-sdk-example": {
                "code": "VN-TGOR-0387",
                "area_ha": 2,
                "yield_kg_per_ha": 10000,
                "name": "Orchard 387",
                "crop": "durian",
                "variety": "Ri6",
                "province": "Tien Giang",
                "district": "Cai Lay",
                "commune": "Ngu Hiep",
                "trees": 240,
                "planted_year": 2015,
                "grower_id": 12,
                "gacc_puc_code": "VNPUC-TG-0387",
                "polygon": {
                  "type": "Polygon",
                  "coordinates": [
                    [
                      [
                        106.1,
                        10.4
                      ],
                      [
                        106.2,
                        10.4
                      ],
                      [
                        106.2,
                        10.5
                      ],
                      [
                        106.1,
                        10.5
                      ],
                      [
                        106.1,
                        10.4
                      ]
                    ]
                  ]
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new growing area.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              },
              "Deprecation": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province`, `district` or `commune`, without `province_code` and `commune_code`), on every answer, errors included. `@1792195200` (RFC 9745): the text-only address was deprecated at the start of 17 October 2026, UTC.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Sunset": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province`, `district` or `commune`, without `province_code` and `commune_code`), on every answer, errors included. `Sat, 01 May 2027 00:00:00 GMT` (RFC 8594): from then a text-only address in Viet Nam may be refused.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Link": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province`, `district` or `commune`, without `province_code` and `commune_code`), on every answer, errors included. `<https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"deprecation\", <https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"sunset\"`: the changelog entry that says what to send instead.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingArea"
                },
                "example": {
                  "code": "VN-TGOR-0387",
                  "tenant": "coop-dl",
                  "name": "Orchard 387",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province": "Tỉnh Đồng Tháp",
                  "district": null,
                  "commune": "Xã Ngũ Hiệp",
                  "area_ha": 2.0,
                  "yield_kg_per_ha": 10000.0,
                  "trees": 240,
                  "planted_year": 2015,
                  "grower_id": 12,
                  "gacc_puc_code": "VNPUC-TG-0387",
                  "source": "manual",
                  "approved_at": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "registry_changed_at": null,
                  "cap_kg": 20000.0,
                  "approval_current": false,
                  "grower": {
                    "id": 12,
                    "tenant": "coop-dl",
                    "display_name": "Co-op member #12",
                    "cooperative": "HTX Ngu Hiep",
                    "public_consent": false,
                    "consent_at": null,
                    "consent_date": null,
                    "consent_scope": null,
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5,
                    "name": "Nguyen Van An"
                  },
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  }
                },
                "x-sdk-example": {
                  "code": "VN-TGOR-0387",
                  "tenant": "coop-dl",
                  "name": "Orchard 387",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "commune": "Ngu Hiep",
                  "area_ha": 2.0,
                  "yield_kg_per_ha": 10000.0,
                  "trees": 240,
                  "planted_year": 2015,
                  "grower_id": 12,
                  "gacc_puc_code": "VNPUC-TG-0387",
                  "source": "manual",
                  "approved_at": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "registry_changed_at": null,
                  "cap_kg": 20000.0,
                  "approval_current": false,
                  "grower": {
                    "id": 12,
                    "tenant": "coop-dl",
                    "display_name": "Co-op member #12",
                    "cooperative": "HTX Ngu Hiep",
                    "public_consent": false,
                    "consent_at": null,
                    "consent_date": null,
                    "consent_scope": null,
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5,
                    "name": "Nguyen Van An"
                  },
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a code that does not look like VN-TGOR-0387, a value out of bounds, an invalid polygon, a grower of another tenant, a crop that names no crop of the crop registry and no configured crop, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header. #273: also a code that is not in the administrative units list in force (`admin_unit_unknown`), a commune that the list places in another province (`commune_not_in_province`), a district (`district_with_codes`) or a province or commune name sent with the codes (`invalid_province` and `invalid_commune`), or a malformed code or one code without the other (`invalid_province_code`, `invalid_commune_code`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_code": {
                    "value": {
                      "error": "invalid code: must look like VN-TGOR-0387",
                      "code": "invalid_code"
                    }
                  },
                  "invalid_area_ha": {
                    "value": {
                      "error": "invalid area_ha: a number above 0 up to 100000",
                      "code": "invalid_area_ha"
                    }
                  },
                  "invalid_polygon": {
                    "value": {
                      "error": "invalid polygon: a ring must be closed (first position equals the last)",
                      "code": "invalid_polygon"
                    }
                  },
                  "invalid_grower_id": {
                    "value": {
                      "error": "invalid grower_id: no such grower in this tenant",
                      "code": "invalid_grower_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "admin_unit_unknown": {
                    "value": {
                      "error": "admin unit unknown: commune 99999 is not in the official list vn-2026-10-17",
                      "code": "admin_unit_unknown"
                    }
                  },
                  "commune_not_in_province": {
                    "value": {
                      "error": "commune not in province: commune 00004 (Phường Ba Đình) is in province 01 (Thành phố Hà Nội), not in 82 (Tỉnh Đồng Tháp)",
                      "code": "commune_not_in_province"
                    }
                  },
                  "district_with_codes": {
                    "value": {
                      "error": "district with codes: Viet Nam has no district level since 2025-07-01; send it null",
                      "code": "district_with_codes"
                    }
                  },
                  "invalid_province": {
                    "value": {
                      "error": "invalid province: absent or null with the codes, the server writes the official name",
                      "code": "invalid_province"
                    }
                  },
                  "invalid_province_code": {
                    "value": {
                      "error": "invalid province_code: the official code, 2 digits as a string, sent with commune_code",
                      "code": "invalid_province_code"
                    }
                  },
                  "invalid_commune_code": {
                    "value": {
                      "error": "invalid commune_code: the official code, 5 digits as a string, sent with province_code",
                      "code": "invalid_commune_code"
                    }
                  },
                  "invalid_commune": {
                    "value": {
                      "error": "invalid commune: absent or null with the codes, the server writes the official name",
                      "code": "invalid_commune"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "Invalid JSON, an unknown field, a code that does not look like VN-TGOR-0387, a value out of bounds, an invalid polygon, a grower of another tenant, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "invalid_json": {
                      "value": {
                        "error": "invalid JSON",
                        "code": "invalid_json"
                      }
                    },
                    "unknown_field": {
                      "value": {
                        "error": "unknown field",
                        "code": "unknown_field"
                      }
                    },
                    "invalid_code": {
                      "value": {
                        "error": "invalid code: must look like VN-TGOR-0387",
                        "code": "invalid_code"
                      }
                    },
                    "invalid_area_ha": {
                      "value": {
                        "error": "invalid area_ha: a number above 0 up to 100000",
                        "code": "invalid_area_ha"
                      }
                    },
                    "invalid_polygon": {
                      "value": {
                        "error": "invalid polygon: a ring must be closed (first position equals the last)",
                        "code": "invalid_polygon"
                      }
                    },
                    "invalid_grower_id": {
                      "value": {
                        "error": "invalid grower_id: no such grower in this tenant",
                        "code": "invalid_grower_id"
                      }
                    },
                    "invalid_idempotency_key": {
                      "value": {
                        "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                        "code": "invalid_idempotency_key"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The code is taken (by any tenant), or the caller's tenant is not registered. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "growing_area_code_already_exists": {
                    "value": {
                      "error": "growing area code already exists",
                      "code": "growing_area_code_already_exists"
                    }
                  },
                  "tenant_not_registered": {
                    "value": {
                      "error": "tenant not registered",
                      "code": "tenant_not_registered"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "503": {
            "description": "#273: `province_code` and `commune_code` were sent but the server has no administrative units list in force to check them (`administrative_units_catalog_unavailable`); nothing was written. A text-only address is not refused this way.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "administrative units catalog unavailable",
                  "code": "administrative_units_catalog_unavailable"
                }
              }
            },
            "x-not-in-sdk": true
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Creates an unapproved area (source `manual`) owned by the tenant the caller acts for; the body cannot name another tenant. The code is the key across all tenants: a taken code is 409 whoever owns it. Audited (`growing_area.create`). Allowed for platform_admin and tenant_admin."
      }
    },
    "/v1/growing-areas/{code}": {
      "get": {
        "operationId": "getGrowingArea",
        "summary": "One growing area",
        "description": "Same roles and consent rules as the list.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "admin_units",
            "in": "query",
            "required": false,
            "description": "#273: `1` adds the address by official code (`province_code`, `commune_code`, `admin_units_version`, `address_status`, `address_before_reform`, `address_candidates`); `0` or none leaves them out and answers exactly as before; any other value is refused (400 `bad admin_units`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "The growing area as the caller may see it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingArea"
                },
                "example": {
                  "code": "VN-TGOR-0387",
                  "tenant": "coop-dl",
                  "name": "Orchard 387",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "commune": "Ngu Hiep",
                  "area_ha": 2.0,
                  "yield_kg_per_ha": 10000.0,
                  "trees": 240,
                  "planted_year": 2015,
                  "grower_id": 12,
                  "gacc_puc_code": "VNPUC-TG-0387",
                  "source": "manual",
                  "approved_at": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "registry_changed_at": null,
                  "cap_kg": 20000.0,
                  "approval_current": false,
                  "grower": {
                    "id": 12,
                    "tenant": "coop-dl",
                    "display_name": "Co-op member #12",
                    "cooperative": "HTX Ngu Hiep",
                    "public_consent": false,
                    "consent_at": null,
                    "consent_date": null,
                    "consent_scope": null,
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5,
                    "name": "Nguyen Van An"
                  },
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "`admin_units` is not 0 or 1, or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_admin_units": {
                    "value": {
                      "error": "bad admin_units",
                      "code": "bad_admin_units"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "$ref": "#/components/responses/BadRequestId"
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateGrowingArea",
        "summary": "Edit a growing area",
        "description": "A tenant_admin of the owner changes the descriptive fields; area_ha, yield_kg_per_ha (the cap inputs of the cross-tenant volume check) and gacc_puc_code are platform_admin only after creation. An unowned (seeded) area is changed by platform_admin only, who may also claim it for a registered tenant once. The code is immutable; approval is kept. Audited (`growing_area.update`, field names only). #273: the address in Viet Nam is given by official code, `province_code` and `commune_code` from `getAdminUnits`; the server writes the official names (`district` null). The text fields `province`, `district` and `commune` are deprecated (sunset 1 May 2027): a text-only address is still accepted, stores the record as not yet coded and answers with the `Deprecation`, `Sunset` and `Link` headers.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowingAreaUpdate"
              },
              "example": {
                "trees": 250,
                "province_code": "82",
                "commune_code": "28516"
              },
              "x-sdk-example": {
                "trees": 250,
                "commune": "Ngu Hiep"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The growing area after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Deprecation": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province`, `district` or `commune`, without `province_code` and `commune_code`), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `@1792195200` (RFC 9745): the text-only address was deprecated at the start of 17 October 2026, UTC.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Sunset": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province`, `district` or `commune`, without `province_code` and `commune_code`), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `Sat, 01 May 2027 00:00:00 GMT` (RFC 8594): from then a text-only address in Viet Nam may be refused.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              },
              "Link": {
                "description": "#273: sent only when the request gave the address in Viet Nam as text only (`province`, `district` or `commune`, without `province_code` and `commune_code`), on every answer, errors included. Not sent when a successful update sends the record's own stored text back unchanged (compared after Unicode NFC normalisation and trimming): that changes no address, the record keeps its codes, status and candidates. `<https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"deprecation\", <https://txng.theio.vn/developers/downloads/CHANGELOG.md#text-only-addresses-of-facilities-growing-areas-and-company-profiles-deprecated-273>; rel=\"sunset\"`: the changelog entry that says what to send instead.",
                "schema": {
                  "type": "string"
                },
                "x-not-in-sdk": true
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingArea"
                },
                "example": {
                  "code": "VN-TGOR-0387",
                  "tenant": "coop-dl",
                  "name": "Orchard 387",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province": "Tỉnh Đồng Tháp",
                  "district": null,
                  "commune": "Xã Ngũ Hiệp",
                  "area_ha": 2.0,
                  "yield_kg_per_ha": 10000.0,
                  "trees": 240,
                  "planted_year": 2015,
                  "grower_id": 12,
                  "gacc_puc_code": "VNPUC-TG-0387",
                  "source": "manual",
                  "approved_at": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "registry_changed_at": null,
                  "cap_kg": 20000.0,
                  "approval_current": false,
                  "grower": {
                    "id": 12,
                    "tenant": "coop-dl",
                    "display_name": "Co-op member #12",
                    "cooperative": "HTX Ngu Hiep",
                    "public_consent": false,
                    "consent_at": null,
                    "consent_date": null,
                    "consent_scope": null,
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5,
                    "name": "Nguyen Van An"
                  },
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  }
                },
                "x-sdk-example": {
                  "code": "VN-TGOR-0387",
                  "tenant": "coop-dl",
                  "name": "Orchard 387",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "commune": "Ngu Hiep",
                  "area_ha": 2.0,
                  "yield_kg_per_ha": 10000.0,
                  "trees": 240,
                  "planted_year": 2015,
                  "grower_id": 12,
                  "gacc_puc_code": "VNPUC-TG-0387",
                  "source": "manual",
                  "approved_at": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "registry_changed_at": null,
                  "cap_kg": 20000.0,
                  "approval_current": false,
                  "grower": {
                    "id": 12,
                    "tenant": "coop-dl",
                    "display_name": "Co-op member #12",
                    "cooperative": "HTX Ngu Hiep",
                    "public_consent": false,
                    "consent_at": null,
                    "consent_date": null,
                    "consent_scope": null,
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5,
                    "name": "Nguyen Van An"
                  },
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, the code in the body, a field the caller may not change, an empty body, a value out of bounds, a grower of another tenant (or on an unowned area), a claim of an owned area, a crop that names no crop of the crop registry and no configured crop, or a bad X-Request-Id. #273: also a code that is not in the administrative units list in force (`admin_unit_unknown`), a commune that the list places in another province (`commune_not_in_province`), a district (`district_with_codes`) or a province or commune name sent with the codes (`invalid_province` and `invalid_commune`), or a malformed code or one code without the other (`invalid_province_code`, `invalid_commune_code`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "code_is_immutable": {
                    "value": {
                      "error": "code is immutable",
                      "code": "code_is_immutable"
                    }
                  },
                  "field_not_editable": {
                    "value": {
                      "error": "field not editable",
                      "code": "field_not_editable"
                    }
                  },
                  "nothing_to_update": {
                    "value": {
                      "error": "nothing to update",
                      "code": "nothing_to_update"
                    }
                  },
                  "invalid_grower_id": {
                    "value": {
                      "error": "invalid grower_id: an unowned area has no growers",
                      "code": "invalid_grower_id"
                    }
                  },
                  "tenant_is_set_already": {
                    "value": {
                      "error": "tenant is set already: an owned area keeps its owner",
                      "code": "tenant_is_set_already"
                    }
                  },
                  "admin_unit_unknown": {
                    "value": {
                      "error": "admin unit unknown: commune 99999 is not in the official list vn-2026-10-17",
                      "code": "admin_unit_unknown"
                    }
                  },
                  "commune_not_in_province": {
                    "value": {
                      "error": "commune not in province: commune 00004 (Phường Ba Đình) is in province 01 (Thành phố Hà Nội), not in 82 (Tỉnh Đồng Tháp)",
                      "code": "commune_not_in_province"
                    }
                  },
                  "district_with_codes": {
                    "value": {
                      "error": "district with codes: Viet Nam has no district level since 2025-07-01; send it null",
                      "code": "district_with_codes"
                    }
                  },
                  "invalid_province": {
                    "value": {
                      "error": "invalid province: absent or null with the codes, the server writes the official name",
                      "code": "invalid_province"
                    }
                  },
                  "invalid_province_code": {
                    "value": {
                      "error": "invalid province_code: the official code, 2 digits as a string, sent with commune_code",
                      "code": "invalid_province_code"
                    }
                  },
                  "invalid_commune_code": {
                    "value": {
                      "error": "invalid commune_code: the official code, 5 digits as a string, sent with province_code",
                      "code": "invalid_commune_code"
                    }
                  },
                  "invalid_commune": {
                    "value": {
                      "error": "invalid commune: absent or null with the codes, the server writes the official name",
                      "code": "invalid_commune"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "Invalid JSON, the code in the body, a field the caller may not change, an empty body, a value out of bounds, a grower of another tenant (or on an unowned area), a claim of an owned area, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "invalid_json": {
                      "value": {
                        "error": "invalid JSON",
                        "code": "invalid_json"
                      }
                    },
                    "code_is_immutable": {
                      "value": {
                        "error": "code is immutable",
                        "code": "code_is_immutable"
                      }
                    },
                    "field_not_editable": {
                      "value": {
                        "error": "field not editable",
                        "code": "field_not_editable"
                      }
                    },
                    "nothing_to_update": {
                      "value": {
                        "error": "nothing to update",
                        "code": "nothing_to_update"
                      }
                    },
                    "invalid_grower_id": {
                      "value": {
                        "error": "invalid grower_id: an unowned area has no growers",
                        "code": "invalid_grower_id"
                      }
                    },
                    "tenant_is_set_already": {
                      "value": {
                        "error": "tenant is set already: an owned area keeps its owner",
                        "code": "tenant_is_set_already"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The tenant an unowned area is claimed for is not registered.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "tenant not registered",
                  "code": "tenant_not_registered"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "503": {
            "description": "#273: `province_code` and `commune_code` were sent but the server has no administrative units list in force to check them (`administrative_units_catalog_unavailable`); nothing was written. A text-only address is not refused this way.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "administrative units catalog unavailable",
                  "code": "administrative_units_catalog_unavailable"
                }
              }
            },
            "x-not-in-sdk": true
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "A tenant_admin of the owner changes the descriptive fields; area_ha, yield_kg_per_ha (the cap inputs of the cross-tenant volume check) and gacc_puc_code are platform_admin only after creation. An unowned (seeded) area is changed by platform_admin only, who may also claim it for a registered tenant once. The code is immutable; approval is kept. Audited (`growing_area.update`, field names only)."
      }
    },
    "/v1/growing-areas/{code}/approve": {
      "post": {
        "operationId": "approveGrowingArea",
        "summary": "Approve a growing area",
        "description": "Marks the area approved; idempotent (approved_at is kept), except that an approval older than the last change of the area's crop or variety is stale and is replaced (`already_approved` false in the audit). Audited (`growing_area.approve`). Allowed for platform_admin only.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The approved growing area.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingArea"
                },
                "example": {
                  "code": "VN-TGOR-0387",
                  "tenant": "coop-dl",
                  "name": "Orchard 387",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province": "Tien Giang",
                  "district": "Cai Lay",
                  "commune": "Ngu Hiep",
                  "area_ha": 2.0,
                  "yield_kg_per_ha": 10000.0,
                  "trees": 240,
                  "planted_year": 2015,
                  "grower_id": 12,
                  "gacc_puc_code": "VNPUC-TG-0387",
                  "source": "manual",
                  "approved_at": 1790000100.0,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "registry_changed_at": null,
                  "cap_kg": 20000.0,
                  "approval_current": true,
                  "grower": {
                    "id": 12,
                    "tenant": "coop-dl",
                    "display_name": "Co-op member #12",
                    "cooperative": "HTX Ngu Hiep",
                    "public_consent": false,
                    "consent_at": null,
                    "consent_date": null,
                    "consent_scope": null,
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5,
                    "name": "Nguyen Van An"
                  },
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/gln": {
      "get": {
        "operationId": "getGrowingAreaGln",
        "summary": "A growing area's GLN",
        "description": "#161: the area's GS1 Global Location Number, null when it has none. Same roles as reading the area (its own and unowned areas). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          }
        ],
        "responses": {
          "200": {
            "description": "The area's GLN.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingAreaGln"
                },
                "example": {
                  "growing_area": "VN-TGOR-0387",
                  "gln": "6141410000014"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "setGrowingAreaGln",
        "summary": "Set, clear or allocate a growing area's GLN",
        "description": "#161: the GLN names the area as read point in the lot's staff EPCIS document; a public document keeps the area's code (a GLN in the GS1 registry can name the grower). Unique among the owner's areas. Same roles as editing the area: an unowned area only for a platform admin (403 otherwise). Audited (`growing_area.gln.set`) in the company's activity log. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GlnChange"
              },
              "example": {
                "allocate": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The GLN as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingAreaGln"
                },
                "example": {
                  "growing_area": "VN-TGOR-0387",
                  "gln": "9520000000004"
                }
              }
            }
          },
          "400": {
            "description": "A body that is not {\"gln\": <13 digits> | null} or {\"allocate\": true}, a GLN whose check digit is wrong or that carries the platform's prefix (allocated only), invalid JSON or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: {\"gln\": \"<13 digits>\" | null} or {\"allocate\": true}",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_gln": {
                    "value": {
                      "error": "invalid gln: 13 digits with a valid GS1 check digit",
                      "code": "invalid_gln"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such record for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Another record of the company has that GLN; or no GS1 company prefix is configured (allocation), or every reference of it is allocated.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "gln_in_use": {
                    "value": {
                      "error": "gln already in use by another facility of the company",
                      "code": "gln_already_in_use_by_another_facility_of_the_company"
                    }
                  },
                  "prefix": {
                    "value": {
                      "error": "prefix not configured: the platform has no GS1 company prefix yet; enter a number of the company's own GS1 membership",
                      "code": "prefix_not_configured"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/polygon-versions": {
      "get": {
        "operationId": "listPolygonVersions",
        "summary": "Boundary versions of a growing area",
        "description": "SENS-A1 (#224): the growing area's pending boundary proposal (null when none) and every boundary the platform approved, newest first with keyset pagination. A version never changes and is in force from its `valid_from` until the next one's. The owning tenant_admin and platform_admin get the boundaries and who proposed and approved them; operators and auditors (and a tenant_admin on an unowned area) get the SHA-256 and times only. Allowed for platform_admin, tenant_admin, auditor and operator; lab is refused. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of versions.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6Mn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "The pending proposal and one page of versions.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PolygonHistory"
                },
                "example": {
                  "pending": {
                    "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
                    "proposed_at": 1790007200.5,
                    "polygon": {
                      "type": "Polygon",
                      "coordinates": [
                        [
                          [
                            106.1,
                            10.4
                          ],
                          [
                            106.2,
                            10.4
                          ],
                          [
                            106.2,
                            10.5
                          ],
                          [
                            106.1,
                            10.5
                          ],
                          [
                            106.1,
                            10.4
                          ]
                        ]
                      ]
                    },
                    "proposed_by": "admin@coop.example"
                  },
                  "items": [
                    {
                      "growing_area": "VN-TGOR-0387",
                      "version": 2,
                      "polygon_sha256": "3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a",
                      "valid_from": 1790003600.0,
                      "origin": "proposal",
                      "polygon": {
                        "type": "Polygon",
                        "coordinates": [
                          [
                            [
                              106.1,
                              10.4
                            ],
                            [
                              106.2,
                              10.4
                            ],
                            [
                              106.2,
                              10.5
                            ],
                            [
                              106.1,
                              10.5
                            ],
                            [
                              106.1,
                              10.4
                            ]
                          ]
                        ]
                      },
                      "proposed_at": 1790000000.5,
                      "proposed_by": "admin@coop.example",
                      "approved_by": "root@croppath.example"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/growing-areas/{code}/boundary-walks": {
      "get": {
        "operationId": "listBoundaryWalks",
        "summary": "Boundary walks of a growing area",
        "description": "#248: the walks sent for the growing area, newest first with keyset pagination, without their tracks: who walked, when, how long, the threshold, the counts and the area. A walk is the evidence of the boundary proposal and of the boundary version with the same `polygon_sha256`; `polygon_sha256` keeps only those. Allowed for the tenant_admin of the area's company and a platform_admin acting for it (X-Tenant); operators, auditors and labs are refused, and it is never public (never an OAuth client). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "polygon_sha256",
            "in": "query",
            "required": false,
            "description": "Only the walks of this outline (64 lower-case hex characters).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6MTd9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of walks.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BoundaryWalkPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 17,
                      "growing_area": "VN-TGOR-0387",
                      "client_walk_id": "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b",
                      "submitted_by": "op@coop.example",
                      "submitted_at": 1790000300.0,
                      "started_at": 1790000000.0,
                      "finished_at": 1790000240.0,
                      "accuracy_threshold_m": 15.0,
                      "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
                      "area_ha": 1.2172891,
                      "registered_area_ha": 2.0,
                      "area_difference_ratio": -0.39135545,
                      "points_total": 6,
                      "points_kept": 5,
                      "points_dropped": 1,
                      "superseded": false
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad cursor, limit or polygon_sha256, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "sha": {
                    "value": {
                      "error": "invalid polygon_sha256: 64 lower-case hex characters",
                      "code": "invalid_polygon_sha256"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operators, auditors and labs do not read walks) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this company: another company's area (and an unowned, seeded one) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "submitBoundaryWalk",
        "summary": "Submit a boundary walk",
        "description": "#248: someone of the company walked the edge of the growing area with a phone: the outline becomes the area's pending boundary proposal and the walk is kept as its evidence. A walk is always a proposal, whoever sends it and whether or not the area is approved: it never changes the boundary in force, it replaces a proposal that was waiting (as a company admin's boundary change does), and a platform admin approves or rejects it in the boundary proposal queue, which records the approved boundary as a new version (approving the boundary does not approve the area). The server checks the outline (one ring, at least 3 different corners, not crossing itself, at least 0.01 ha, every corner one of the submitted points within the accuracy threshold) and computes its area. Idempotent on the area and `client_walk_id`: the same walk sent again answers the stored result (200) and changes nothing; another walk with the same id is 409. Audited (`growing_area.boundary_walk.submit`, one row per request naming the walk, the outline's SHA-256 and the counts, never the track or coordinates). Allowed for operator, tenant_admin and a platform_admin acting for the company (X-Tenant), never an OAuth client; auditors and labs are refused. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BoundaryWalkCreate"
              },
              "example": {
                "client_walk_id": "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b",
                "polygon": {
                  "type": "Polygon",
                  "coordinates": [
                    [
                      [
                        106.1,
                        10.4
                      ],
                      [
                        106.101,
                        10.4
                      ],
                      [
                        106.101,
                        10.401
                      ],
                      [
                        106.1,
                        10.401
                      ],
                      [
                        106.1,
                        10.4
                      ]
                    ]
                  ]
                },
                "accuracy_threshold_m": 15,
                "started_at": 1790000000.0,
                "finished_at": 1790000240.0,
                "points": [
                  [
                    106.1,
                    10.4,
                    4.0,
                    1790000000.0
                  ],
                  [
                    106.1005,
                    10.4,
                    3.5,
                    1790000030.0
                  ],
                  [
                    106.1004,
                    10.4003,
                    32.0,
                    1790000040.0
                  ],
                  [
                    106.101,
                    10.4,
                    4.2,
                    1790000060.0
                  ],
                  [
                    106.101,
                    10.401,
                    3.8,
                    1790000150.0
                  ],
                  [
                    106.1,
                    10.401,
                    4.0,
                    1790000240.0
                  ]
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The walk was stored and its outline is the area's pending boundary proposal.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BoundaryWalkResult"
                },
                "example": {
                  "id": 17,
                  "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
                  "area_ha": 1.2172891,
                  "registered_area_ha": 2.0,
                  "area_difference_ratio": -0.39135545,
                  "points_total": 6,
                  "points_kept": 5,
                  "points_dropped": 1,
                  "superseded": false
                }
              }
            }
          },
          "200": {
            "description": "The same walk was sent before: its stored result; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BoundaryWalkResult"
                },
                "example": {
                  "id": 17,
                  "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
                  "area_ha": 1.2172891,
                  "registered_area_ha": 2.0,
                  "area_difference_ratio": -0.39135545,
                  "points_total": 6,
                  "points_kept": 5,
                  "points_dropped": 1,
                  "superseded": false
                }
              }
            }
          },
          "400": {
            "description": "An unknown, missing or malformed field (a time before 2020 or more than 300 s ahead included), an outline that is not a Polygon of exactly one ring or has more than 1000 positions, or an outline the walk does not support: fewer than 3 different corners (`too_few_corners`), crossing itself (`self_intersecting`), under 0.01 ha (`too_small`), a corner that is not one of the submitted points within the accuracy threshold (`vertex_not_walked`). Or a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "self_intersecting": {
                    "value": {
                      "error": "self_intersecting: the boundary crosses itself",
                      "code": "self_intersecting"
                    }
                  },
                  "too_small": {
                    "value": {
                      "error": "too_small: the walked area is under 0.01 ha",
                      "code": "too_small"
                    }
                  },
                  "too_few_corners": {
                    "value": {
                      "error": "too_few_corners: the boundary needs at least 3 different corners",
                      "code": "too_few_corners"
                    }
                  },
                  "vertex_not_walked": {
                    "value": {
                      "error": "vertex_not_walked: every corner must be a walked point within the accuracy threshold",
                      "code": "vertex_not_walked"
                    }
                  },
                  "one_ring": {
                    "value": {
                      "error": "invalid polygon: a walk is a Polygon with exactly one ring",
                      "code": "invalid_polygon"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (auditors and labs; also anyone on an unowned, seeded area, which has no company to propose for), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions), or company read-only while the company is leaving CropPath or has left.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this company: another company's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "Another walk was already sent with this `client_walk_id` for the area. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "walk_id_taken": {
                    "value": {
                      "error": "client_walk_id taken: another walk was sent with this id",
                      "code": "client_walk_id_taken"
                    }
                  },
                  "idempotency_in_progress": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/boundary-walks/{id}": {
      "get": {
        "operationId": "getBoundaryWalk",
        "summary": "A boundary walk with its track",
        "description": "#248: one walk of the growing area with its outline and its raw track (every fix, the imprecise ones included). Allowed for the tenant_admin of the area's company and a platform_admin acting for it (X-Tenant); operators, auditors and labs are refused, and it is never public (never an OAuth client). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The walk's id.",
            "schema": {
              "type": "integer",
              "minimum": 1
            },
            "example": 17
          }
        ],
        "responses": {
          "200": {
            "description": "The walk.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BoundaryWalk"
                },
                "example": {
                  "id": 17,
                  "growing_area": "VN-TGOR-0387",
                  "client_walk_id": "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b",
                  "submitted_by": "op@coop.example",
                  "submitted_at": 1790000300.0,
                  "started_at": 1790000000.0,
                  "finished_at": 1790000240.0,
                  "accuracy_threshold_m": 15.0,
                  "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
                  "area_ha": 1.2172891,
                  "registered_area_ha": 2.0,
                  "area_difference_ratio": -0.39135545,
                  "points_total": 6,
                  "points_kept": 5,
                  "points_dropped": 1,
                  "superseded": false,
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.101,
                          10.4
                        ],
                        [
                          106.101,
                          10.401
                        ],
                        [
                          106.1,
                          10.401
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  },
                  "points": [
                    [
                      106.1,
                      10.4,
                      4.0,
                      1790000000.0
                    ],
                    [
                      106.1005,
                      10.4,
                      3.5,
                      1790000030.0
                    ],
                    [
                      106.1004,
                      10.4003,
                      32.0,
                      1790000040.0
                    ],
                    [
                      106.101,
                      10.4,
                      4.2,
                      1790000060.0
                    ],
                    [
                      106.101,
                      10.401,
                      3.8,
                      1790000150.0
                    ],
                    [
                      106.1,
                      10.401,
                      4.0,
                      1790000240.0
                    ]
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operators, auditors and labs do not read walks) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such walk of this growing area of this company: another company's area or walk, or a walk of another area, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 17",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/land-certificates": {
      "get": {
        "operationId": "listLandCertificates",
        "summary": "Land certificates of a growing area",
        "description": "#250: the land-use right certificates sent for the growing area, newest first with keyset pagination, without their corners: the central meridian, the number of corners, the plane area, the photo's hash, the converted outline's SHA-256 and area, compared with the registered size and with the area's latest boundary walk. A certificate is the evidence of the boundary proposal and of the boundary version with the same `polygon_sha256` (that boundary is \"from land certificate\"); `polygon_sha256` keeps only those. Allowed for the tenant_admin of the area's company and a platform_admin acting for it (X-Tenant); operators, auditors and labs are refused, and it is never public (never an OAuth client). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "polygon_sha256",
            "in": "query",
            "required": false,
            "description": "Only the certificates of this outline (64 lower-case hex characters).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6MTd9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of certificates.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LandCertificatePage"
                },
                "example": {
                  "items": [
                    {
                      "id": 5,
                      "growing_area": "VN-TGOR-0387",
                      "submitted_at": 1790000300.0,
                      "central_meridian_min": 6345,
                      "corners_total": 4,
                      "plane_area_m2": 12110.71,
                      "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c",
                      "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
                      "area_ha": 1.2188975,
                      "registered_area_ha": 2.0,
                      "area_difference_ratio": -0.39055124,
                      "walk": {
                        "walk_id": 17,
                        "area_ha": 1.2172891,
                        "area_difference_ratio": 0.00132129,
                        "centre_offset_m": 0.02
                      },
                      "superseded": false
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad cursor, limit or polygon_sha256, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "sha": {
                    "value": {
                      "error": "invalid polygon_sha256: 64 lower-case hex characters",
                      "code": "invalid_polygon_sha256"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operators, auditors and labs do not read land certificates) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this company: another company's area (and an unowned, seeded one) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "submitLandCertificate",
        "summary": "Submit a land certificate's parcel corners",
        "description": "#250: the corners of the parcel printed on a land-use right certificate's parcel map, VN-2000 plane coordinates (X northing, Y easting in metres) of the 3-degree transverse Mercator projection with k0 = 0.9999 on the province's central meridian (Circular 26/2024/TT-BTNMT), with the photo of the certificate page. The server converts the corners to WGS 84 with the transformation the government published (Decision 05/2007/QD-BTNMT's parameters in Circular 973/2001/TT-TCDC's formulas): the outline becomes the area's pending boundary proposal and the certificate is kept as its evidence. A certificate is always a proposal, whoever sends it and whether or not the area is approved: it never changes the boundary in force, it replaces a proposal that was waiting, and a platform admin approves or rejects it in the boundary proposal queue, which records the approved boundary as a new version. The answer compares the outline with the registered size and with the area's latest boundary walk. The published sources give no control points: the conversion's accuracy against official points is not established. Audited (`growing_area.land_certificate.submit`, one row per request naming the certificate, the outline's SHA-256, the central meridian and the number of corners, never the corners or the photo). Allowed for the tenant_admin of the area's company and a platform_admin acting for it (X-Tenant); operators, auditors and labs are refused, and it is never public (never an OAuth client). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LandCertificateCreate"
              },
              "example": {
                "central_meridian_min": 6345,
                "corners": [
                  [
                    1150116.67,
                    538126.67
                  ],
                  [
                    1150116.79,
                    538236.17
                  ],
                  [
                    1150227.39,
                    538236.05
                  ],
                  [
                    1150227.27,
                    538126.55
                  ]
                ],
                "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The certificate was stored and its outline is the area's pending boundary proposal.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LandCertificate"
                },
                "example": {
                  "id": 5,
                  "growing_area": "VN-TGOR-0387",
                  "submitted_at": 1790000300.0,
                  "central_meridian_min": 6345,
                  "corners_total": 4,
                  "plane_area_m2": 12110.71,
                  "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c",
                  "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
                  "area_ha": 1.2188975,
                  "registered_area_ha": 2.0,
                  "area_difference_ratio": -0.39055124,
                  "walk": {
                    "walk_id": 17,
                    "area_ha": 1.2172891,
                    "area_difference_ratio": 0.00132129,
                    "centre_offset_m": 0.02
                  },
                  "superseded": false,
                  "corners": [
                    [
                      1150116.67,
                      538126.67
                    ],
                    [
                      1150116.79,
                      538236.17
                    ],
                    [
                      1150227.39,
                      538236.05
                    ],
                    [
                      1150227.27,
                      538126.55
                    ]
                  ],
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.09999996,
                          10.39999998
                        ],
                        [
                          106.10100002,
                          10.39999997
                        ],
                        [
                          106.10100004,
                          10.40099996
                        ],
                        [
                          106.09999998,
                          10.40099996
                        ],
                        [
                          106.09999996,
                          10.39999998
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "An unknown, missing or malformed field: a central meridian that is not one of Circular 26/2024/TT-BTNMT Appendix 01, a photo hash that is not 64 lower-case hex characters, fewer than 3 or more than 200 corners, a corner out of range; an image the company did not upload (`unknown_photo_sha256`); or an outline the server refuses: fewer than 3 different corners (`too_few_corners`), crossing itself (`self_intersecting`), under 0.01 ha (`too_small`). Or a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "meridian": {
                    "value": {
                      "error": "invalid central_meridian_min: a central meridian of Circular 26/2024/TT-BTNMT Appendix 01",
                      "code": "invalid_central_meridian_min"
                    }
                  },
                  "photo": {
                    "value": {
                      "error": "unknown photo_sha256: upload the photo of the certificate (JPEG or PNG) first",
                      "code": "unknown_photo_sha256"
                    }
                  },
                  "self_intersecting": {
                    "value": {
                      "error": "self_intersecting: the boundary crosses itself",
                      "code": "self_intersecting"
                    }
                  },
                  "too_small": {
                    "value": {
                      "error": "too_small: the parcel is under 0.01 ha",
                      "code": "too_small"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operators, auditors and labs; also anyone on an unowned, seeded area, which has no company to propose for), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions), or company read-only while the company is leaving CropPath or has left.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this company: another company's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "idempotency key in use: retry later",
                  "code": "idempotency_key_in_use"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/land-certificates/check": {
      "post": {
        "operationId": "checkLandCertificate",
        "summary": "Check a land certificate's parcel corners before its photo",
        "description": "#250: the refusals a land certificate (submitLandCertificate) would meet before its photo matters, for the same corners and central meridian without `photo_sha256`: the corners, the converted outline (`too_few_corners`, `self_intersecting`, `too_small`) and the area (another company's area 404, an unowned one 403). Nothing is stored and the request is not audited; the answer is the outline the certificate would propose. The console calls it before it uploads the certificate's photo, so a refused certificate never leaves the land user's certificate page behind as an ordinary company upload (readable to auditors and API clients through the upload's activity log row). Allowed for the tenant_admin of the area's company and a platform_admin acting for it (X-Tenant); operators, auditors and labs are refused, and it is never public (never an OAuth client). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LandCertificateCheck"
              },
              "example": {
                "central_meridian_min": 6345,
                "corners": [
                  [
                    1150116.67,
                    538126.67
                  ],
                  [
                    1150116.79,
                    538236.17
                  ],
                  [
                    1150227.39,
                    538236.05
                  ],
                  [
                    1150227.27,
                    538126.55
                  ]
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The certificate would pass these checks: the outline it would propose. Nothing was stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LandCertificateCheckResult"
                },
                "example": {
                  "corners_total": 4,
                  "plane_area_m2": 12110.71,
                  "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
                  "area_ha": 1.2188975,
                  "registered_area_ha": 2.0,
                  "area_difference_ratio": -0.39055124,
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.09999996,
                          10.39999998
                        ],
                        [
                          106.10100002,
                          10.39999997
                        ],
                        [
                          106.10100004,
                          10.40099996
                        ],
                        [
                          106.09999998,
                          10.40099996
                        ],
                        [
                          106.09999996,
                          10.39999998
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "An unknown, missing or malformed field (`photo_sha256` included: a check never takes the photo): a central meridian that is not one of Circular 26/2024/TT-BTNMT Appendix 01, fewer than 3 or more than 200 corners, a corner out of range; or an outline the server refuses: fewer than 3 different corners (`too_few_corners`), crossing itself (`self_intersecting`), under 0.01 ha (`too_small`). Or a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "meridian": {
                    "value": {
                      "error": "invalid central_meridian_min: a central meridian of Circular 26/2024/TT-BTNMT Appendix 01",
                      "code": "invalid_central_meridian_min"
                    }
                  },
                  "self_intersecting": {
                    "value": {
                      "error": "self_intersecting: the boundary crosses itself",
                      "code": "self_intersecting"
                    }
                  },
                  "too_small": {
                    "value": {
                      "error": "too_small: the parcel is under 0.01 ha",
                      "code": "too_small"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operators, auditors and labs; also anyone on an unowned, seeded area, which has no company to propose for), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions), or company read-only while the company is leaving CropPath or has left.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this company: another company's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "idempotency key in use: retry later",
                  "code": "idempotency_key_in_use"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/land-certificates/{id}": {
      "get": {
        "operationId": "getLandCertificate",
        "summary": "A land certificate with its corners",
        "description": "#250: one land certificate of the growing area with its corners as typed and the converted outline (WGS 84). Allowed for the tenant_admin of the area's company and a platform_admin acting for it (X-Tenant); operators, auditors and labs are refused, and it is never public (never an OAuth client). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The certificate's id.",
            "schema": {
              "type": "integer",
              "minimum": 1
            },
            "example": 5
          }
        ],
        "responses": {
          "200": {
            "description": "The certificate.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LandCertificate"
                },
                "example": {
                  "id": 5,
                  "growing_area": "VN-TGOR-0387",
                  "submitted_at": 1790000300.0,
                  "central_meridian_min": 6345,
                  "corners_total": 4,
                  "plane_area_m2": 12110.71,
                  "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c",
                  "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
                  "area_ha": 1.2188975,
                  "registered_area_ha": 2.0,
                  "area_difference_ratio": -0.39055124,
                  "walk": {
                    "walk_id": 17,
                    "area_ha": 1.2172891,
                    "area_difference_ratio": 0.00132129,
                    "centre_offset_m": 0.02
                  },
                  "superseded": false,
                  "corners": [
                    [
                      1150116.67,
                      538126.67
                    ],
                    [
                      1150116.79,
                      538236.17
                    ],
                    [
                      1150227.39,
                      538236.05
                    ],
                    [
                      1150227.27,
                      538126.55
                    ]
                  ],
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.09999996,
                          10.39999998
                        ],
                        [
                          106.10100002,
                          10.39999997
                        ],
                        [
                          106.10100004,
                          10.40099996
                        ],
                        [
                          106.09999998,
                          10.40099996
                        ],
                        [
                          106.09999996,
                          10.39999998
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (operators, auditors and labs do not read land certificates) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such certificate of this growing area of this company: another company's area or certificate, or a certificate of another area, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 5",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/sensor-series": {
      "get": {
        "operationId": "getSensorSeries",
        "summary": "Sensor series of a growing area",
        "description": "SENS-B1e (#235): the hourly, daily (UTC days) or farm-day (`local_daily`, #365) summaries of one vocabulary capability in the growing area, from the caller's company's devices only (an unowned area shows each company its own readings), one series per depth unless `depth_cm` names one. Each bucket gives the minimum, maximum, mean and count of the values flagged pass or not evaluated (mean null when none counted), every reading's count and the count per QC flag. A bucket is returned when its start is from the start of the bucket holding `from` to before `to`. A `local_daily` bucket is the merge of the 24 hourly summaries of one Asia/Ho_Chi_Minh day (its least minimum, greatest maximum, summed sums and counts), so it is exact over the whole history; its `bucket_start` is the day's local midnight and the answer adds `time_zone` and `day_starts_at`. The range is at most 31 days hourly, 5 years daily and 366 days `local_daily` (`range_too_long`); the answer at most 5000 buckets (`truncated`). No coordinate is ever part of a series. Allowed for platform_admin, tenant_admin, auditor and operator; lab is refused. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "capability",
            "in": "query",
            "required": true,
            "description": "A capability of the vocabulary (`capability_is_required`, `unknown_capability`).",
            "schema": {
              "type": "string"
            },
            "example": "soil.moisture"
          },
          {
            "name": "depth_cm",
            "in": "query",
            "required": false,
            "description": "One depth in cm, 0 to 10000; omitted: every depth, each its own series.",
            "schema": {
              "type": "number",
              "minimum": 0,
              "maximum": 10000
            },
            "example": 30
          },
          {
            "name": "grain",
            "in": "query",
            "required": false,
            "description": "Bucket width: an hour or a day in UTC (`hourly`, `daily`: a UTC day runs from 07:00 to 07:00 in Viet Nam), or a farm day in Asia/Ho_Chi_Minh (`local_daily`).",
            "schema": {
              "type": "string",
              "enum": [
                "hourly",
                "daily",
                "local_daily"
              ],
              "default": "hourly"
            },
            "example": "hourly"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Start: an ISO 8601 date or date-time (+07:00 without an offset). Default: 7 days (hourly) or 365 days (daily, local_daily) before `to`.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-01T00:00:00+07:00"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "End (excluded), as `from`. Default: now.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-01T00:00:00+07:00"
          }
        ],
        "responses": {
          "200": {
            "description": "The series.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SensorSeries"
                },
                "example": {
                  "growing_area": "VN-TGOR-0387",
                  "capability": "soil.moisture",
                  "unit": "%",
                  "grain": "hourly",
                  "bucket_s": 3600.0,
                  "from": 1790125200.0,
                  "to": 1790730000.0,
                  "truncated": false,
                  "series": [
                    {
                      "depth_cm": 10.0,
                      "buckets": [
                        {
                          "bucket_start": 1790726400.0,
                          "min": 30.7,
                          "max": 31.1,
                          "mean": 30.9,
                          "count": 2,
                          "n_total": 3,
                          "n_pass": 2,
                          "n_not_evaluated": 0,
                          "n_suspect": 0,
                          "n_fail": 0,
                          "n_missing": 1
                        },
                        {
                          "bucket_start": 1790730000.0,
                          "min": null,
                          "max": null,
                          "mean": null,
                          "count": 0,
                          "n_total": 1,
                          "n_pass": 0,
                          "n_not_evaluated": 0,
                          "n_suspect": 0,
                          "n_fail": 1,
                          "n_missing": 0
                        }
                      ]
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A missing or unknown capability, a bad grain, depth or time, a range whose start is not before its end or longer than the grain allows, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "capability_is_required": {
                    "value": {
                      "error": "capability is required",
                      "code": "capability_is_required"
                    }
                  },
                  "unknown_capability": {
                    "value": {
                      "error": "unknown capability",
                      "code": "unknown_capability"
                    }
                  },
                  "bad_grain": {
                    "value": {
                      "error": "bad grain: hourly, daily or local_daily",
                      "code": "bad_grain"
                    }
                  },
                  "bad_depth_cm": {
                    "value": {
                      "error": "bad depth_cm",
                      "code": "bad_depth_cm"
                    }
                  },
                  "bad_from": {
                    "value": {
                      "error": "bad from",
                      "code": "bad_from"
                    }
                  },
                  "bad_to": {
                    "value": {
                      "error": "bad to",
                      "code": "bad_to"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range: from must be before to",
                      "code": "bad_range"
                    }
                  },
                  "range_too_long": {
                    "value": {
                      "error": "range too long",
                      "code": "range_too_long"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/growing-areas/{code}/location-check": {
      "get": {
        "operationId": "getAreaLocationCheck",
        "summary": "Location check of a growing area",
        "description": "#247: which location check ingest makes now for the caller's company's positions of the growing area, in plain terms for the console: against its approved plot boundary (`plot_boundary`), else against its registered commune with the commune boundaries the platform imported from OpenStreetMap (`commune`: a mismatch is an alert only, never a hold, and the location trust is unchanged), else none. For the commune check: whether the registered commune is a commune of the boundary data (a name from before the 2025-07-01 reform is not, and gets only `commune_unknown`), the commune verdict counts over a range of reception times (at most 31 days; both ends included), and, only for a platform admin and the operators and admins (tenant_admin) of the area's owning company, the communes the area's judged positions fell in (the area mapped by point). The OpenStreetMap attribution comes with every answer that names a dataset. Never public. Allowed for platform_admin, tenant_admin, auditor and operator; lab is refused; another company's area answers 404. Not part of the partner SDK clients (`x-not-in-sdk`).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Start: an ISO 8601 date or date-time (+07:00 without an offset). Default: 7 days before `to`.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-01T00:00:00+07:00"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "End (included), as `from`. Default: now.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-01T00:00:00+07:00"
          }
        ],
        "responses": {
          "200": {
            "description": "Which check applies, and the area by point.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LocationCheck"
                },
                "example": {
                  "applies": "commune",
                  "registered_commune": "Long Trung",
                  "dataset": "osm-2026-10-15T20:21:00Z",
                  "name": "unmatched",
                  "commune_verdict_counts": {
                    "commune_match": 0,
                    "commune_mismatch": 0,
                    "commune_unknown": 12
                  },
                  "position_communes": [
                    {
                      "name": "Xã Mẫu Một",
                      "osm_relation": 101,
                      "positions": 12
                    }
                  ],
                  "attribution": "© OpenStreetMap contributors",
                  "copyright": "https://www.openstreetmap.org/copyright"
                }
              }
            }
          },
          "400": {
            "description": "A bad time, a range whose start is not before its end or longer than 31 days, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_from": {
                    "value": {
                      "error": "bad from",
                      "code": "bad_from"
                    }
                  },
                  "bad_to": {
                    "value": {
                      "error": "bad to",
                      "code": "bad_to"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range: from must be before to",
                      "code": "bad_range"
                    }
                  },
                  "range_too_long": {
                    "value": {
                      "error": "range too long",
                      "code": "range_too_long"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/growing-areas/{code}/verdict-map": {
      "get": {
        "operationId": "getVerdictMap",
        "summary": "Verdict map of a growing area",
        "description": "SENS-B1e (#235): for a range of reception times (at most 31 days; both ends included), every device of the caller's company bound to the growing area by its current placement or whose positions were judged against the area in the range (at most 500, `truncated`): its profile, a summary of its current placement, how many positions got each geofence verdict and its latest verdict with the time it was judged. The install point and the latest judged position are given only to a platform admin and to the operators and admins (tenant_admin) of the area's owning company (`coordinates_shown`); an auditor, and every caller but a platform admin on an unowned area, get the same answer without them. The boundary only to whom the growing-area read gives it. Never public. Allowed for platform_admin, tenant_admin, auditor and operator; lab is refused. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Start: an ISO 8601 date or date-time (+07:00 without an offset). Default: 7 days before `to`.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-01T00:00:00+07:00"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "End (included), as `from`. Default: now.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "2026-10-01T00:00:00+07:00"
          }
        ],
        "responses": {
          "200": {
            "description": "The devices and their verdicts.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/VerdictMap"
                },
                "example": {
                  "growing_area": "VN-TGOR-0387",
                  "from": 1790121600.0,
                  "to": 1790726400.0,
                  "coordinates_shown": true,
                  "truncated": false,
                  "devices": [
                    {
                      "device_id": "knk-1",
                      "profile": "vn.agritrace.durian-knocker",
                      "placement": {
                        "version": 1,
                        "mobility": "fixed",
                        "growing_area": "VN-TGOR-0387",
                        "bound_here": true,
                        "depth_cm": 30.0,
                        "installed_at": 1790000000.0,
                        "removed_at": null,
                        "install_point": {
                          "lat": 10.45,
                          "lon": 106.15,
                          "accuracy_m": 2.0
                        }
                      },
                      "verdict_counts": {
                        "inside": 41,
                        "near": 2,
                        "outside": 1,
                        "ambiguous": 0,
                        "unverifiable": 0,
                        "no_position": 0,
                        "no_polygon": 0
                      },
                      "latest_verdict": "inside",
                      "latest_verdict_at": 1790726400.0,
                      "latest_position": {
                        "lat": 10.4501,
                        "lon": 106.1502,
                        "acc_m": 3.0,
                        "verdict": "inside",
                        "checked_at": 1790726400.0
                      }
                    }
                  ],
                  "polygon": {
                    "type": "Polygon",
                    "coordinates": [
                      [
                        [
                          106.1,
                          10.4
                        ],
                        [
                          106.2,
                          10.4
                        ],
                        [
                          106.2,
                          10.5
                        ],
                        [
                          106.1,
                          10.5
                        ],
                        [
                          106.1,
                          10.4
                        ]
                      ]
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad time, a range whose start is not before its end or longer than 31 days, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_from": {
                    "value": {
                      "error": "bad from",
                      "code": "bad_from"
                    }
                  },
                  "bad_to": {
                    "value": {
                      "error": "bad to",
                      "code": "bad_to"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range: from must be before to",
                      "code": "bad_range"
                    }
                  },
                  "range_too_long": {
                    "value": {
                      "error": "range too long",
                      "code": "range_too_long"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/growing-areas/{code}/certifications": {
      "get": {
        "operationId": "listCertifications",
        "summary": "Certifications of a growing area",
        "description": "Newest first with keyset pagination. Each certification's status is judged against today's UTC date. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused. #269 review: `verified=1` adds each certification's `verified`, the server's own judgement of whether it is verified (see Certification); the console shows it instead of repeating the rule. The parameter and the field are not part of the partner SDK clients (`x-not-in-sdk`).",
        "x-sdk-description": "Newest first with keyset pagination. Each certification's status is judged against today's UTC date. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of certifications.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6MTJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "verified",
            "in": "query",
            "required": false,
            "description": "#269 review: `1` adds each certification's `verified` (`items[].verified`); `0` or none leaves it out and answers exactly as before; any other value is refused (400 `bad verified`). It selects no certifications: every one is listed either way.",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "One page of certifications.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CertificationPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 1,
                      "growing_area": "VN-TGOR-0387",
                      "scheme": "VietGAP",
                      "number": "VG-TG-0387",
                      "issuer": "NAFIQAD",
                      "valid_from": "2025-01-01",
                      "valid_to": "2027-12-31",
                      "evidence_sha256": null,
                      "created_at": 1790000000.5,
                      "status": "valid"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, `verified` not 0 or 1, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_verified": {
                    "value": {
                      "error": "bad verified",
                      "code": "bad_verified"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "bad_cursor": {
                      "value": {
                        "error": "bad cursor",
                        "code": "bad_cursor"
                      }
                    },
                    "bad_limit": {
                      "value": {
                        "error": "bad limit",
                        "code": "bad_limit"
                      }
                    },
                    "bad_request_id": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createCertification",
        "summary": "Record a certification",
        "description": "Adds a certification to an area of the caller's tenant (a platform_admin also to an unowned area). The same scheme and number recorded again on the area is refused (409), except when the stored certification is unverified and this request is verified (never for ISO 22000, FSSC 22000, BRCGS or IFS, which are now recorded on the facility, #269): that request verifies the stored certification in place (the same `id`; its `issuer`, validity and `evidence_sha256` become the request's and `created_at` the time of the change) and answers 201 with it. Audited (`growing_area.certification.create`). Allowed for platform_admin and tenant_admin.",
        "x-sdk-description": "Adds a certification to an area of the caller's tenant (a platform_admin also to an unowned area). Audited (`growing_area.certification.create`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CertificationCreate"
              },
              "example": {
                "scheme": "VietGAP",
                "number": "VG-TG-0387",
                "issuer": "NAFIQAD",
                "valid_from": "2025-01-01",
                "valid_to": "2027-12-31",
                "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
              },
              "x-sdk-example": {
                "scheme": "VietGAP",
                "number": "VG-TG-0387",
                "issuer": "NAFIQAD",
                "valid_from": "2025-01-01",
                "valid_to": "2027-12-31"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new certification, or the unverified one this request verified.",
            "x-sdk-description": "The new certification.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Certification"
                },
                "example": {
                  "id": 1,
                  "growing_area": "VN-TGOR-0387",
                  "scheme": "VietGAP",
                  "number": "VG-TG-0387",
                  "issuer": "NAFIQAD",
                  "valid_from": "2025-01-01",
                  "valid_to": "2027-12-31",
                  "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "created_at": 1790000000.5,
                  "status": "valid"
                },
                "x-sdk-example": {
                  "id": 1,
                  "growing_area": "VN-TGOR-0387",
                  "scheme": "VietGAP",
                  "number": "VG-TG-0387",
                  "issuer": "NAFIQAD",
                  "valid_from": "2025-01-01",
                  "valid_to": "2027-12-31",
                  "evidence_sha256": null,
                  "created_at": 1790000000.5,
                  "status": "valid"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_valid_to": {
                    "value": {
                      "error": "invalid valid_to: not before valid_from",
                      "code": "invalid_valid_to"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The same scheme and number is already recorded for this area, verified, or this request would not verify it. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "x-sdk-description": "The same scheme and number is already recorded for this area. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "certification_already_recorded": {
                    "value": {
                      "error": "certification already recorded",
                      "code": "certification_already_recorded"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/satellite-checks": {
      "get": {
        "operationId": "listSatelliteChecks",
        "summary": "Satellite checks of a growing area",
        "description": "Newest first with keyset pagination. Recorded by hand (source `manual`); automatic Sentinel-2 fetching is not part of this API. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of satellite checks.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6MTJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of satellite checks.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SatelliteCheckPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 1,
                      "growing_area": "VN-TGOR-0387",
                      "image_date": "2026-09-20",
                      "provider": "sentinel-2",
                      "result": "match",
                      "cultivated_ha": 1.9,
                      "deforestation": false,
                      "confidence": 0.86,
                      "image_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c",
                      "source": "manual",
                      "created_at": 1790000000.5
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createSatelliteCheck",
        "summary": "Record a satellite check",
        "description": "Adds a satellite check to an area of the caller's tenant (a platform_admin also to an unowned area). Audited (`growing_area.satellite_check.create`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SatelliteCheckCreate"
              },
              "example": {
                "image_date": "2026-09-20",
                "provider": "sentinel-2",
                "result": "match",
                "cultivated_ha": 1.9,
                "deforestation": false,
                "confidence": 0.86,
                "image_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new satellite check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SatelliteCheck"
                },
                "example": {
                  "id": 1,
                  "growing_area": "VN-TGOR-0387",
                  "image_date": "2026-09-20",
                  "provider": "sentinel-2",
                  "result": "match",
                  "cultivated_ha": 1.9,
                  "deforestation": false,
                  "confidence": 0.86,
                  "image_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c",
                  "source": "manual",
                  "created_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_result": {
                    "value": {
                      "error": "invalid result: one of match, mismatch, inconclusive",
                      "code": "invalid_result"
                    }
                  },
                  "invalid_deforestation": {
                    "value": {
                      "error": "invalid deforestation: a boolean",
                      "code": "invalid_deforestation"
                    }
                  },
                  "invalid_image_sha256": {
                    "value": {
                      "error": "invalid image_sha256: 64 lower-case hex characters",
                      "code": "invalid_image_sha256"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/sprays": {
      "get": {
        "operationId": "listSprayRecords",
        "summary": "Spray records of a growing area",
        "description": "Newest first with keyset pagination. Each record carries safe_from (sprayed_on + withholding_days) and its withholding_status against the harvest date: violated when sprayed_on <= harvest_date < safe_from, so a harvest on safe_from is ok. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "harvest_date",
            "in": "query",
            "required": false,
            "description": "The harvest date (YYYY-MM-DD) to judge withholding against; today's UTC date when omitted.",
            "schema": {
              "type": "string",
              "format": "date",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2026-09-14"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of spray records.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6MTJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of spray records.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SprayRecordPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "growing_area": "VN-TGOR-0387",
                      "sprayed_on": "2026-09-01",
                      "product": "Ridomil Gold",
                      "active_ingredient": "metalaxyl-M",
                      "withholding_days": 14,
                      "evidence_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c",
                      "created_at": 1790000000.5,
                      "safe_from": "2026-09-15",
                      "evaluated_on": "2026-09-14",
                      "withholding_status": "violated"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, a malformed harvest_date, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_harvest_date": {
                    "value": {
                      "error": "invalid harvest_date: a date YYYY-MM-DD from 1900 to 2100",
                      "code": "invalid_harvest_date"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createSprayRecord",
        "summary": "Record a spray record",
        "description": "Adds a spray record to an area of the caller's tenant (a platform_admin also to an unowned area). Audited (`growing_area.spray.create`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SprayRecordCreate"
              },
              "example": {
                "sprayed_on": "2026-09-01",
                "product": "Ridomil Gold",
                "active_ingredient": "metalaxyl-M",
                "withholding_days": 14,
                "evidence_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new spray record.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SprayRecord"
                },
                "example": {
                  "id": 3,
                  "growing_area": "VN-TGOR-0387",
                  "sprayed_on": "2026-09-01",
                  "product": "Ridomil Gold",
                  "active_ingredient": "metalaxyl-M",
                  "withholding_days": 14,
                  "evidence_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c",
                  "created_at": 1790000000.5,
                  "safe_from": "2026-09-15",
                  "evaluated_on": "2026-09-14",
                  "withholding_status": "violated"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_sprayed_on": {
                    "value": {
                      "error": "invalid sprayed_on: a date YYYY-MM-DD from 1900 to 2100",
                      "code": "invalid_sprayed_on"
                    }
                  },
                  "invalid_withholding_days": {
                    "value": {
                      "error": "invalid withholding_days: an integer from 0 to 365",
                      "code": "invalid_withholding_days"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/volume": {
      "get": {
        "operationId": "getGrowingAreaVolume",
        "summary": "Cap and headroom of a growing area for a season",
        "description": "Queries.volume for the area (declared kg summed across all tenants, cap = area_ha x yield_kg_per_ha) plus headroom_kg = cap_kg - declared_kg. The area must be readable by the caller (own or unowned). Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "season",
            "in": "query",
            "required": true,
            "description": "Season label (the calendar year by default).",
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9._-]{1,32}$"
            },
            "example": "2026"
          }
        ],
        "responses": {
          "200": {
            "description": "Cap, declared volume and headroom.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowingAreaVolume"
                },
                "example": {
                  "growing_area": "VN-TGOR-0387",
                  "season": "2026",
                  "declared_kg": 2000.0,
                  "cap_kg": 20000.0,
                  "headroom_kg": 18000.0
                }
              }
            }
          },
          "400": {
            "description": "A missing or malformed season, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "season_is_required": {
                    "value": {
                      "error": "season is required",
                      "code": "season_is_required"
                    }
                  },
                  "invalid_season": {
                    "value": {
                      "error": "invalid season: 1 to 32 letters, digits, dots, hyphens or underscores",
                      "code": "invalid_season"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/ingest/{route}": {
      "post": {
        "operationId": "ingestEnvelope",
        "summary": "Receive a signed envelope from a device or gateway",
        "description": "The path parameter `route` spans `{tenant}/{site}/{device}/{kind}[/{eventType}]` and includes slashes (the server pattern is `/v1/ingest/{route*}`). The body is a signed envelope (envelope version 1, `spec` `agritrace.iot/1.0`), which the server validates against its full schema, served at /developers/downloads/envelope-v1.schema.json (event types at /developers/downloads/event-types-v1.json, capabilities at /developers/downloads/capabilities-v1.json, device profiles below /developers/downloads/profiles/); that schema is not inlined here, so the request schema is open (`additionalProperties: true`). Over mTLS the certificate CN must match the device or its gateway. Statuses: 202 accepted or quarantined, 409 duplicate, 503 for a rejection that may resolve itself (unknown_device, unknown_key), other rejections 4xx. Every outcome that comes from the ingest service carries an IngestResult body; 400 and 413 can also come from the HTTP layer with an Error body. A `pack` event (#136: profile vn.agritrace.pack-station, one `pack.carton` reading per carton, the seal number in `context.seal`) is compared with the lot's packing records: the lot, its facility and the sending device's, the seal number (the lot's pack seal once it is packed), and every carton's fruits and net mass. Any difference is quarantined with the reason `pack_mismatch: <differences>` and a high `pack_mismatch` alert, and holds the lot until it is reviewed. A `status` envelope whose device id is a registered gateway's is that gateway's status heartbeat (#24, profile vn.agritrace.gateway): signed with one of the gateway's own keys, over mTLS from that gateway, with the readings of that profile only, else it is rejected (`profile_mismatch`, `invalid_content`, `key_not_authorized`). It is not stored as an envelope: the server keeps the gateway's newest heartbeat (GET /v1/gateways/{id}/heartbeat), and answers 202 `accepted`, or 409 `duplicate` for the heartbeat it keeps and, with the reason `superseded`, for an older one. Ordering: by `seq`, except for signed heartbeats, which also carry the gateway's own clock: a signed heartbeat with a lower `seq` but a later time than the kept one is kept (a gateway that was reset counts its `seq` from 0 again), and a signed heartbeat with a higher `seq` but an earlier time is answered `superseded`; an unsigned one is ordered by `seq` alone. A heartbeat dated more than the server's maximum future skew past its clock is rejected with 400 `future_timestamp` (a device envelope gets a 202 quarantine instead), so it never freezes the kept one. The other rejection reasons are those of a device envelope. #134: a message over its company's ingest quota (the company of the certificate's device or gateway, whatever the route names) answers 429 `too_many_requests` with `Retry-After` and an Error body before the body is read; the device sends it again later. A request without a client certificate (plain HTTP, or TLS without one), or with a certificate of no registered device or gateway (which the ingest then rejects), never takes a company's quota: it takes its client address's own bucket, of the default ingest quota, and answers the same 429 over it.",
        "x-sdk-description": "The path parameter `route` spans `{tenant}/{site}/{device}/{kind}[/{eventType}]` and includes slashes (the server pattern is `/v1/ingest/{route*}`). The body is a signed envelope (envelope version 1, `spec` `agritrace.iot/1.0`), which the server validates against its full schema, served at /developers/downloads/envelope-v1.schema.json (event types at /developers/downloads/event-types-v1.json, capabilities at /developers/downloads/capabilities-v1.json, device profiles below /developers/downloads/profiles/); that schema is not inlined here, so the request schema is open (`additionalProperties: true`). Over mTLS the certificate CN must match the device or its gateway. Statuses: 202 accepted or quarantined, 409 duplicate, 503 for a rejection that may resolve itself (unknown_device, unknown_key), other rejections 4xx. Every outcome that comes from the ingest service carries an IngestResult body; 400 and 413 can also come from the HTTP layer with an Error body. A `pack` event (#136: profile vn.agritrace.pack-station, one `pack.carton` reading per carton, the seal number in `context.seal`) is compared with the lot's packing records: the lot, its facility and the sending device's, the seal number (the lot's pack seal once it is packed), and every carton's fruits and net mass. Any difference is quarantined with the reason `pack_mismatch: <differences>` and a high `pack_mismatch` alert, and holds the lot until it is reviewed.",
        "tags": [
          "ingest"
        ],
        "security": [
          {
            "deviceMtls": []
          }
        ],
        "parameters": [
          {
            "name": "route",
            "in": "path",
            "required": true,
            "description": "`{tenant}/{site}/{device}/{kind}[/{eventType}]`, slashes included.",
            "schema": {
              "type": "string"
            },
            "allowReserved": true,
            "example": "coop-dl/ph1/knk-1/event/inspect"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Envelope"
              },
              "example": {
                "spec": "agritrace.iot/1.0",
                "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                "kind": "event",
                "eventType": "inspect",
                "device": {
                  "id": "knk-1",
                  "profile": "vn.agritrace.durian-knocker@1.0.0",
                  "gateway": "gw-01"
                },
                "time": "2026-09-30T08:00:00.000+07:00",
                "seq": 0,
                "context": {
                  "lot": "LOT-A",
                  "facility": "66-DL-SR-0001-CHN"
                },
                "readings": [
                  {
                    "capability": "produce.maturity_index",
                    "value": 82.0,
                    "unit": "%"
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "Stored. `status` is accepted or quarantined (held for review, see `reasons`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IngestResult"
                },
                "examples": {
                  "accepted": {
                    "value": {
                      "status": "accepted",
                      "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                      "reasons": []
                    }
                  },
                  "quarantined": {
                    "value": {
                      "status": "quarantined",
                      "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                      "reasons": [
                        "volume_exceeds_cap"
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Rejected as malformed (malformed, unsupported_spec, bad_route, route_mismatch, bad_time; IngestResult), or a bad X-Request-Id (Error).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/IngestResult"
                    },
                    {
                      "$ref": "#/components/schemas/Error"
                    }
                  ]
                },
                "examples": {
                  "rejected": {
                    "value": {
                      "status": "rejected",
                      "id": null,
                      "reasons": [
                        "malformed"
                      ]
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Rejected: missing_signature or bad_signature.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IngestResult"
                },
                "example": {
                  "status": "rejected",
                  "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                  "reasons": [
                    "bad_signature"
                  ]
                }
              }
            }
          },
          "403": {
            "description": "Rejected: key_not_authorized, peer_mismatch, tenant_mismatch, device_inactive or company_read_only (SELF-2-4, #193: the device's company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IngestResult"
                },
                "example": {
                  "status": "rejected",
                  "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                  "reasons": [
                    "tenant_mismatch"
                  ]
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "Duplicate of a stored envelope (same id and content). Permanent for the sender; nothing was changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IngestResult"
                },
                "example": {
                  "status": "duplicate",
                  "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                  "reasons": []
                }
              }
            }
          },
          "413": {
            "description": "Rejected as payload_too_large (IngestResult), or the request body is over 1 MiB (Error).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/IngestResult"
                    },
                    {
                      "$ref": "#/components/schemas/Error"
                    }
                  ]
                },
                "examples": {
                  "rejected": {
                    "value": {
                      "status": "rejected",
                      "id": null,
                      "reasons": [
                        "payload_too_large"
                      ]
                    }
                  },
                  "body_too_large": {
                    "value": {
                      "error": "body too large",
                      "code": "body_too_large"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Rejected: id_conflict (same id, different content). An alert is raised.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IngestResult"
                },
                "example": {
                  "status": "rejected",
                  "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                  "reasons": [
                    "id_conflict"
                  ]
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "Rejected with unknown_device or unknown_key: the registry may catch up, so the sender retries.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IngestResult"
                },
                "example": {
                  "status": "rejected",
                  "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                  "reasons": [
                    "unknown_device"
                  ]
                }
              }
            }
          }
        }
      }
    },
    "/v1/keys": {
      "get": {
        "operationId": "listKeys",
        "summary": "Device and gateway keys of the caller's tenant",
        "description": "Keys ordered by kid, with keyset pagination (at most 100 per page); a key belongs to its owner's tenant. With `owner`, only that device's or gateway's keys. Never returns key material, only fingerprints. Allowed for platform_admin, tenant_admin and auditor.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "owner",
            "in": "query",
            "required": false,
            "description": "A device or gateway id of the caller's tenant.",
            "schema": {
              "type": "string"
            },
            "example": "knk-1"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of keys.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6Imtuay0xIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of keys.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/KeyPage"
                },
                "example": {
                  "items": [
                    {
                      "kid": "knk-1-2026",
                      "owner_type": "device",
                      "owner_id": "knk-1",
                      "status": "active",
                      "created_at": 1790000000.5,
                      "revoked_at": null,
                      "revoke_reason": null,
                      "revoked_by": null,
                      "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                      "fingerprint": "19fc…e0d9",
                      "approval": "approved"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id, or a malformed owner.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "invalid_owner": {
                    "value": {
                      "error": "invalid owner: a device or gateway id",
                      "code": "invalid_owner"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "`owner` is not a device or gateway of the caller's tenant (missing and foreign alike).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createKey",
        "summary": "Register a public key for a device or gateway",
        "description": "Adds an active key. The PEM must be one `PUBLIC KEY` block holding an EC P-256 SubjectPublicKeyInfo (private keys, certificates, other curves and trailing data are refused); the canonical PEM is stored. The kid must be unused by every tenant and not reserved by the deployed seed (provisioning reserves every seed kid). #201: the key waits for a platform admin's approval whatever its owner's (an approved device or gateway is listed in the pending queue again); until then evidence it signs counts as Self-declared. Audited (`key.create`; the row keeps the kid and fingerprint, never the PEM). Allowed for platform_admin and tenant_admin. Second admin approval (INTEGRITY-3, #203): while the company requires a second admin (PUT /v1/company/four-eyes), a direct call answers 403 `second_admin_approval_required` before anything is done (no audit row, no Idempotency-Key used): ask for it with POST /v1/approval-requests, and another admin of the company approves it.",
        "x-sdk-description": "Adds an active key. The PEM must be one `PUBLIC KEY` block holding an EC P-256 SubjectPublicKeyInfo (private keys, certificates, other curves and trailing data are refused); the canonical PEM is stored. The kid must be unused by every tenant and not reserved by the deployed seed (provisioning reserves every seed kid). #201: the key waits for a platform admin's approval whatever its owner's (an approved device or gateway is listed in the pending queue again); until then evidence it signs counts as Self-declared. Audited (`key.create`; the row keeps the kid and fingerprint, never the PEM). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/KeyCreate"
              },
              "example": {
                "kid": "knk-1-2026",
                "owner_type": "device",
                "owner_id": "knk-1",
                "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhaFFjV3QAoRFgCMO0lO2g8XMPeCX\n0MemwTpR6thzbANTI0unLVbZ1TwEmvZdARGAPji8g2MlIm1UAXv95sLWcg==\n-----END PUBLIC KEY-----\n"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Key"
                },
                "example": {
                  "kid": "knk-1-2026",
                  "owner_type": "device",
                  "owner_id": "knk-1",
                  "status": "active",
                  "created_at": 1790000000.5,
                  "revoked_at": null,
                  "revoke_reason": null,
                  "revoked_by": null,
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "approval": "pending"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a malformed kid or owner, an owner type other than device or gateway, an unacceptable PEM, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_kid": {
                    "value": {
                      "error": "invalid kid: 1 to 128 letters, digits, '.', '_', ':' or '-', starting with a letter or digit",
                      "code": "invalid_kid"
                    }
                  },
                  "invalid_owner_type": {
                    "value": {
                      "error": "invalid owner_type: device or gateway",
                      "code": "invalid_owner_type"
                    }
                  },
                  "invalid_public_key_pem": {
                    "value": {
                      "error": "invalid public_key_pem: an EC P-256 public key as PEM SubjectPublicKeyInfo",
                      "code": "invalid_public_key_pem"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The owner is not a device or gateway of the caller's tenant (missing and foreign alike).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The kid is used (in any tenant; the owner is not revealed) or reserved by the seed; both answer alike. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_id_taken": {
                    "value": {
                      "error": "key id taken",
                      "code": "key_id_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/keys/{kid}/revoke": {
      "post": {
        "operationId": "revokeKey",
        "summary": "Revoke a key",
        "description": "Marks the key revoked with its reason; ingest refuses it from then on. `compromise` also raises one high-severity `key_compromised` alert for the tenant. A revoked key cannot be revoked again (the first reason and time stay). Audited (`key.revoke`). Allowed for platform_admin and tenant_admin. Step-up (#87): a signed-in session of an account with two-step sign-in must have confirmed a code from its authenticator app (or a backup code) within the last 5 minutes and its password within the last 10 minutes, else 401 `mfa_step_up_required` before anything is done (no audit row): confirm both with POST /v1/auth/reauth, then repeat the request. A session of an account without two-step sign-in, API tokens and API clients are served as before.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "kid",
            "in": "path",
            "required": true,
            "description": "Key id.",
            "schema": {
              "type": "string"
            },
            "example": "knk-1-2026"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/KeyRevoke"
              },
              "example": {
                "reason": "rotation"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The key after revocation.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Key"
                },
                "example": {
                  "kid": "knk-1-2026",
                  "owner_type": "device",
                  "owner_id": "knk-1",
                  "status": "revoked",
                  "created_at": 1790000000.5,
                  "revoked_at": 1790086400.0,
                  "revoke_reason": "rotation",
                  "revoked_by": "admin@coop.example",
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "approval": "approved"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a reason other than rotation or compromise, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: rotation or compromise",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            },
            "x-sdk-description": "No valid session, API token or legacy token."
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such key for this tenant: a key of another tenant's device or gateway answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-1-2026",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The key is already revoked. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_already_revoked": {
                    "value": {
                      "error": "key already revoked",
                      "code": "key_already_revoked"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Marks the key revoked with its reason; ingest refuses it from then on. `compromise` also raises one high-severity `key_compromised` alert for the tenant. A revoked key cannot be revoked again (the first reason and time stay). Audited (`key.revoke`). Allowed for platform_admin and tenant_admin."
      }
    },
    "/v1/lots": {
      "get": {
        "operationId": "listLots",
        "summary": "Lots of the caller's tenant",
        "description": "Newest first (by seq) with keyset pagination, optionally only one status or facility. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJzZXEiOjE0fQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only lots in this status.",
            "schema": {
              "enum": [
                "draft",
                "open",
                "paused",
                "closed",
                "packed",
                "shipped",
                "recalled",
                "withdrawn"
              ]
            },
            "example": "open"
          },
          {
            "name": "facility",
            "in": "query",
            "required": false,
            "description": "Only lots of this facility.",
            "schema": {
              "type": "string",
              "maxLength": 256
            },
            "example": "VN-TGPH-021"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of lots.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotPage"
                },
                "example": {
                  "items": [
                    {
                      "tenant": "coop-dl",
                      "code": "LO-260928-014",
                      "seq": 14,
                      "public_id": "5f0c8e2a9b7d4c1e8a3f6b2d9c0e7a14",
                      "facility": "VN-TGPH-021",
                      "product": "durian",
                      "variety": "Ri6",
                      "growing_area": "VN-TGOR-0387",
                      "harvest_date": "2026-09-27",
                      "harvest_event_id": null,
                      "destination": "Huu Nghi border gate, Lang Son",
                      "gtin": "00012345678905",
                      "status": "open",
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5,
                      "closed_at": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor this API did not issue, a limit outside 1 to 200, an unknown status, a facility value over 256 characters, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_status": {
                    "value": {
                      "error": "bad status",
                      "code": "bad_status"
                    }
                  },
                  "bad_facility": {
                    "value": {
                      "error": "bad facility",
                      "code": "bad_facility"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createLot",
        "summary": "Create a lot",
        "description": "Creates a `draft` lot owned by the tenant the caller acts for, with the next lot number (seq) of the tenant and a random public id. The code is unique within the tenant (the same code in another tenant is another lot) and immutable. Audited (`lot.create`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LotCreate"
              },
              "example": {
                "code": "LO-260928-014",
                "facility": "VN-TGPH-021",
                "variety": "Ri6",
                "growing_area": "VN-TGOR-0387",
                "harvest_date": "2026-09-27",
                "destination": "Huu Nghi border gate, Lang Son"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new lot.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Lot"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "LO-260928-014",
                  "seq": 14,
                  "public_id": "5f0c8e2a9b7d4c1e8a3f6b2d9c0e7a14",
                  "facility": "VN-TGPH-021",
                  "product": "durian",
                  "variety": "Ri6",
                  "growing_area": "VN-TGOR-0387",
                  "harvest_date": "2026-09-27",
                  "harvest_event_id": null,
                  "destination": "Huu Nghi border gate, Lang Son",
                  "gtin": "00012345678905",
                  "status": "draft",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "closed_at": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad code, a facility that is missing, of another tenant or outside an operator's facilities, an unknown growing area or harvest event, a bad GTIN or date, a value out of bounds, a product that names no crop of the crop registry and no configured crop, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "x-sdk-description": "Invalid JSON, an unknown field, a bad code, a facility that is missing, of another tenant or outside an operator's facilities, an unknown growing area or harvest event, a bad GTIN or date, a value out of bounds, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_code": {
                    "value": {
                      "error": "invalid code: 3 to 40 upper-case letters, digits or '-', starting with a letter or digit",
                      "code": "invalid_code"
                    }
                  },
                  "unknown_facility": {
                    "value": {
                      "error": "unknown facility",
                      "code": "unknown_facility"
                    }
                  },
                  "unknown_growing_area": {
                    "value": {
                      "error": "unknown growing area",
                      "code": "unknown_growing_area"
                    }
                  },
                  "unknown_harvest_event": {
                    "value": {
                      "error": "unknown harvest event",
                      "code": "unknown_harvest_event"
                    }
                  },
                  "invalid_gtin": {
                    "value": {
                      "error": "invalid gtin: 14 digits with a valid GS1 check digit",
                      "code": "invalid_gtin"
                    }
                  },
                  "invalid_harvest_date": {
                    "value": {
                      "error": "invalid harvest_date: later than today",
                      "code": "invalid_harvest_date"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The tenant already has a lot with this code. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded). SELF-2-8 (#197): or the facility is a company's proposal CropPath has not approved yet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_code_already_exists": {
                    "value": {
                      "error": "lot code already exists",
                      "code": "lot_code_already_exists"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  },
                  "facility_not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/suggested-code": {
      "get": {
        "operationId": "suggestLotCode",
        "summary": "A suggested code for the next lot",
        "description": "#315: the code the console's create-lot form pre-fills, `LO-YYMMDD-NNN`: YYMMDD is today in Asia/Ho_Chi_Minh and NNN the number after the highest one the selected company (X-Tenant) used that day in a code of this form (three digits, zero-padded; more digits past 999), or the lowest free number when that would make the code longer than 40 characters. It is counted over the whole company, whatever the caller's packing houses, because lot codes are unique within the company. The code stays the company's choice: any code `createLot` accepts may be sent instead. Nothing is reserved, so two callers may get the same suggestion: `createLot` refuses the second (409 `lot_code_already_exists`), and a new suggestion is the next number. Read-only and not audited (a read). Allowed for the callers who may create a lot: platform_admin, tenant_admin and an operator signed in with a session; auditors and lab users are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the console's create-lot form.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The suggested code.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotCodeSuggestion"
                },
                "example": {
                  "code": "LO-261019-001"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/lots/{lot}": {
      "get": {
        "operationId": "getLot",
        "summary": "One lot",
        "description": "The lot of the caller's tenant with this code. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Lot"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "LO-260928-014",
                  "seq": 14,
                  "public_id": "5f0c8e2a9b7d4c1e8a3f6b2d9c0e7a14",
                  "facility": "VN-TGPH-021",
                  "product": "durian",
                  "variety": "Ri6",
                  "growing_area": "VN-TGOR-0387",
                  "harvest_date": "2026-09-27",
                  "harvest_event_id": null,
                  "destination": "Huu Nghi border gate, Lang Son",
                  "gtin": "00012345678905",
                  "status": "open",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "closed_at": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateLot",
        "summary": "Edit a lot",
        "description": "Changes descriptive fields while the lot is draft or open. The GTIN freezes once the lot has fruit records. Audited (`lot.update`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LotUpdate"
              },
              "example": {
                "variety": "Ri6",
                "destination": null
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The lot after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Lot"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "LO-260928-014",
                  "seq": 14,
                  "public_id": "5f0c8e2a9b7d4c1e8a3f6b2d9c0e7a14",
                  "facility": "VN-TGPH-021",
                  "product": "durian",
                  "variety": "Ri6",
                  "growing_area": "VN-TGOR-0387",
                  "harvest_date": "2026-09-27",
                  "harvest_event_id": null,
                  "destination": "Huu Nghi border gate, Lang Son",
                  "gtin": "00012345678905",
                  "status": "open",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "closed_at": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an immutable or unknown field, an empty body, an invalid value, a product that names no crop of the crop registry and no configured crop, or a bad X-Request-Id.",
            "x-sdk-description": "Invalid JSON, an immutable or unknown field, an empty body, an invalid value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "immutable": {
                    "value": {
                      "error": "code is immutable",
                      "code": "code_is_immutable"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "empty": {
                    "value": {
                      "error": "nothing to update",
                      "code": "nothing_to_update"
                    }
                  },
                  "invalid_gtin": {
                    "value": {
                      "error": "invalid gtin: 14 digits with a valid GS1 check digit",
                      "code": "invalid_gtin"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot is no longer editable, or the GTIN is frozen.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "closed": {
                    "value": {
                      "error": "lot is closed",
                      "code": "lot_is_closed"
                    }
                  },
                  "gtin_frozen": {
                    "value": {
                      "error": "gtin is frozen: the lot already has fruit records",
                      "code": "gtin_is_frozen"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/epcis": {
      "get": {
        "operationId": "getLotEpcis",
        "summary": "EPCIS 2.0 document of one lot",
        "description": "An EPCIS 2.0 JSON-LD document built from the lot's accepted events, then the departure of the lot's shipment (#153): a shipping ObjectEvent (disposition in_transit, `agri:shipment` the shipment code) whose `bizTransactionList` lists the shipment's document references as `urn:agritrace:bt:<type>:<number>` with their CBV 2.0 types (inv, bol, desadv, cert, testres; none for a customs declaration or another document). Its `eventID` is derived from the departure and that list: documents amended after the departure give the event a new `eventID` that supersedes the earlier one (an EPCIS event is immutable and receivers deduplicate by `eventID`), and unchanged documents keep it. The consignee is not in it, and the public EPCIS document carries none of this. Its structure is defined by the EPCIS standard, so the schema is open (`additionalProperties: true`). A lot code that is not one of the tenant's (unknown, or another tenant's) answers 200 with a document without events, never 404. With `version=2` the lot's daily sensor summaries follow its other events (see that parameter).",
        "x-sdk-description": "An EPCIS 2.0 JSON-LD document built from the lot's accepted events, then the departure of the lot's shipment (#153): a shipping ObjectEvent (disposition in_transit, `agri:shipment` the shipment code) whose `bizTransactionList` lists the shipment's document references as `urn:agritrace:bt:<type>:<number>` with their CBV 2.0 types (inv, bol, desadv, cert, testres; none for a customs declaration or another document). Its `eventID` is derived from the departure and that list: documents amended after the departure give the event a new `eventID` that supersedes the earlier one (an EPCIS event is immutable and receivers deduplicate by `eventID`), and unchanged documents keep it. The consignee is not in it, and the public EPCIS document carries none of this. Its structure is defined by the EPCIS standard, so the schema is open (`additionalProperties: true`). A lot code that is not one of the tenant's (unknown, or another tenant's) answers 200 with a document without events, never 404.",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "trace_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Traceability lot code.",
            "schema": {
              "type": "string"
            },
            "example": "LOT-A"
          },
          {
            "name": "version",
            "in": "query",
            "required": false,
            "description": "The mapping version (#238). `2` appends the daily sensor summaries of the lot's growing area: one ObjectEvent per device and UTC day (action OBSERVE, bizStep sensor_reporting, read point the growing area, no objects, event time the day's last reading) over the 31 UTC days ending with the day of the lot's harvest date (its creation date without one), only days that have ended, from the company's own readings. Its sensor element names the device (`deviceID`), the day (`startTime`, `endTime`) and the mapping (`dataProcessingMethod` `agri:method/daily-summary-v2`), and, when the deployment's public origin is configured, links the device's metadata (`deviceMetadata`, `GET /v1/devices/{id}/metadata`) and its telemetry envelopes received while the day's readings were (`rawData`, a `GET /v1/envelopes` query): staff reads, never public. One sensorReport per numeric capability and depth: `minValue`, `maxValue` and `meanValue` over the readings the quality checks passed or did not evaluate (absent when there is none), `uom`, `agri:depthCm`, `agri:readingCount`, `agri:valueCount`, `agri:qcFlag` (the least trusted quality flag among the readings: 4 fail, then 3 suspect, 9 missing, 2 not evaluated, 1 pass) and `agri:calibrationId` (the calibrations in force). The event carries the location evidence, never a coordinate: `agri:geoVerdict` (the geofence verdict that weighs most that day), `agri:geoDistM` (the largest signed distance to the boundary in metres, negative inside), `agri:accM` (the largest reported accuracy in metres) and `agri:osnma` (the least assured Galileo OSNMA status the device's positions report). A late reading that changes a day's summary gives the day a new `eventID`. `3` appends the same daily events, with three differences: each report takes the type and unit of CropPath's export mapping of each capability (a GS1 CBV measurement type as the bare term the GS1 EPCIS 2.0 JSON schema lists, such as `VolumeFraction`, or a CropPath type URI `https://agritrace.vn/voc/<name>`; `uom` the UN/ECE Recommendation 20 code, or, where there is none, the UCUM unit as `agri:ucum`) and names its capability (`agri:capability`) and what was measured (`agri:feature`); the device's own GNSS fixes of the day follow as two reports of type `Angle`, `component` `latitude` and `longitude`, `coordinateReferenceSystem` `http://www.opengis.net/def/crs/OGC/1.3/CRS84`, `uom` `DD`, with their `minValue`, `maxValue` and `meanValue` (no mean longitude when the fixes span more than 180 degrees of longitude), so a device with positions only has an event too; and `dataProcessingMethod` is `agri:method/daily-summary-v3`, the `eventID` another than in version 2. Coordinates appear only in this staff document, never in the public one. `2` stays exactly as described above. `1` or none: the document without them, exactly as before; any other value is refused (400 `bad version`).",
            "schema": {
              "type": "string",
              "enum": [
                "1",
                "2",
                "3"
              ]
            },
            "example": "2",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "EPCIS document.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/ld+json": {
                "schema": {
                  "$ref": "#/components/schemas/EpcisDocument"
                },
                "example": {
                  "@context": [
                    "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld"
                  ],
                  "type": "EPCISDocument",
                  "schemaVersion": "2.0",
                  "epcisBody": {
                    "eventList": []
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/events": {
      "get": {
        "operationId": "listLotEvents",
        "summary": "Accepted events of one lot",
        "description": "Accepted `event` envelopes of the caller's tenant for the lot, ordered by event time then sequence. Each item is the stored envelope (envelope version 1, see `Envelope`) plus `_status`. A lot code that is not one of the tenant's (unknown, or another tenant's) answers 200 with an empty array, never 404.",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "trace_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Traceability lot code.",
            "schema": {
              "type": "string"
            },
            "example": "LOT-A"
          }
        ],
        "responses": {
          "200": {
            "description": "Stored envelopes (an empty array when the lot has none).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/StoredEnvelope"
                  }
                },
                "example": [
                  {
                    "spec": "agritrace.iot/1.0",
                    "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                    "kind": "event",
                    "eventType": "inspect",
                    "device": {
                      "id": "knk-1",
                      "profile": "vn.agritrace.durian-knocker@1.0.0",
                      "gateway": "gw-01"
                    },
                    "time": "2026-09-30T08:00:00.000+07:00",
                    "seq": 0,
                    "context": {
                      "lot": "LOT-A",
                      "facility": "66-DL-SR-0001-CHN"
                    },
                    "readings": [
                      {
                        "capability": "produce.maturity_index",
                        "value": 82.0,
                        "unit": "%"
                      }
                    ],
                    "_status": "accepted"
                  }
                ]
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/fruits": {
      "get": {
        "operationId": "listLotFruits",
        "summary": "Fruits of a lot",
        "description": "The lot's fruits in allocation order (n ascending, across all of its sessions) with keyset pagination, optionally only one status and/or the codes starting with `q`. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "q",
            "in": "query",
            "required": false,
            "description": "Fruit code prefix, case-insensitive: 1 to 32 letters, digits or '-'.",
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9-]{1,32}$"
            },
            "example": "Q-014-01"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only fruits with this status.",
            "schema": {
              "type": "string",
              "enum": [
                "awaiting_device",
                "recorded",
                "overridden",
                "rejected",
                "remeasured"
              ]
            },
            "example": "recorded"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJuIjoxMjh9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the lot's fruits.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FruitPage"
                },
                "example": {
                  "items": [
                    {
                      "tenant": "coop-dl",
                      "code": "Q-014-0129",
                      "n": 129,
                      "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                      "lot": "LO-260928-014",
                      "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                      "line": "A2",
                      "operator": "user-7",
                      "status": "recorded",
                      "labels_printed_at": 1790000000.5,
                      "created_at": 1790000000.5,
                      "updated_at": 1790560561.2,
                      "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                      "level": 3,
                      "level_pred": 3,
                      "maturity_class": "mature",
                      "confidence": 0.91,
                      "model": "sf100-m3",
                      "measured_at": 1790560560.0,
                      "weight_kg": 2.84,
                      "level_sensory": null,
                      "override": false,
                      "pending_review": false,
                      "grade": "A",
                      "eating_window": {
                        "start_days": 3,
                        "end_days": 4,
                        "from_date": "2026-10-01",
                        "to_date": "2026-10-02",
                        "band": "ambient",
                        "warning": null
                      },
                      "record_tier": "device_recorded",
                      "knock_envelope_id": "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30",
                      "scale_envelope_id": "6e3a1d9c-2b7f-4e8a-b5c4-9d0f1e2a3b47",
                      "override_envelope_id": null
                    }
                  ],
                  "next_cursor": "eyJuIjoxMjl9"
                }
              }
            }
          },
          "400": {
            "description": "A query that is not a code prefix, an unknown status, a cursor this API did not issue, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_query": {
                    "value": {
                      "error": "bad query",
                      "code": "bad_query"
                    }
                  },
                  "bad_status": {
                    "value": {
                      "error": "bad status",
                      "code": "bad_status"
                    }
                  },
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/fsma.csv": {
      "get": {
        "operationId": "getLotFsmaCsv",
        "summary": "FSMA 204 sortable spreadsheet of one lot",
        "description": "One row per critical tracking event of the lot, sorted by time: its signed device events, the departure of its shipment and the lot merges it took part in, with the FSMA 204 key data elements (#158). The columns are the FsmaRow schema's. A lot code that is not one of the tenant's (unknown, or another tenant's) answers 200 with the header row only, never 404.",
        "x-sdk-description": "One row per critical tracking event of the lot, sorted by time. Columns: traceability_lot_code, critical_tracking_event, event_date, event_time, location, quantity, unit_of_measure, growing_area, parcel, producer, device_id, event_id. A lot code that is not one of the tenant's (unknown, or another tenant's) answers 200 with the header row only, never 404.",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "trace_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Traceability lot code.",
            "schema": {
              "type": "string"
            },
            "example": "LOT-A"
          }
        ],
        "responses": {
          "200": {
            "description": "CSV with a header row, then one row per critical tracking event sorted by time; the columns are the FsmaRow schema's, in its order. A text cell starting with =, +, -, @, a tab or a carriage return gets a leading ' so a spreadsheet never runs it as a formula.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "traceability_lot_code,critical_tracking_event,event_date,event_time,location,quantity,unit_of_measure,growing_area,parcel,producer,device_id,event_id,commodity,variety,field_name,traceability_lot_code_source,traceability_lot_code_source_reference,shipper_location_name,shipper_location_address,shipper_location_gln,recipient_location_name,recipient_location_address,recipient_location_gln,reference_document_type,reference_document_number,container,input_traceability_lot_code,input_quantity\r\n",
                "x-sdk-example": "traceability_lot_code,critical_tracking_event,event_date,event_time,location,quantity,unit_of_measure,growing_area,parcel,producer,device_id,event_id\r\n"
              }
            },
            "x-sdk-description": "CSV with a header row."
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/sessions": {
      "get": {
        "operationId": "listLotSessions",
        "summary": "Measurement sessions of a lot",
        "description": "Every measurement session of the lot, newest first (by opened_at), each with the devices chosen when it opened. Not paginated: a line holds at most one open or paused session, so a lot has few. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's measurement sessions, newest first.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MeasurementSessionList"
                },
                "example": {
                  "items": [
                    {
                      "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                      "tenant": "coop-dl",
                      "lot": "LO-260928-014",
                      "facility": "VN-TGPH-021",
                      "line": "A2",
                      "status": "open",
                      "opened_by": "operator@coop.example",
                      "opened_at": 1790000000.5,
                      "paused_at": null,
                      "closed_at": null,
                      "updated_at": 1790000000.5,
                      "devices": [
                        "knk-1",
                        "scale-1"
                      ]
                    },
                    {
                      "id": "8c4a2d1e-5b6f-4e3a-9d7c-1f0b2e4a6c58",
                      "tenant": "coop-dl",
                      "lot": "LO-260928-014",
                      "facility": "VN-TGPH-021",
                      "line": "A1",
                      "status": "closed",
                      "opened_by": "operator@coop.example",
                      "opened_at": 1789990000.5,
                      "paused_at": null,
                      "closed_at": 1789995000.5,
                      "updated_at": 1789995000.5,
                      "devices": [
                        "knk-1"
                      ]
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "openMeasurementSession",
        "summary": "Open a measurement session",
        "description": "Opens a session of the lot on one line of the lot's facility (a draft lot becomes open), records the chosen devices, then sends `set_session {lot, line[, operator]}` to each chosen device whose profile declares it (`operator` is `user-<id>` for a signed-in user). A device without set_session is skipped and a transport failure is reported per device; neither undoes the session. A lot that was sampled (`POST /v1/lots/{lot}/samples`) takes no new session: 409 lot sampled, its export population is final. Audited (`session.open`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MeasurementSessionOpen"
              },
              "example": {
                "line": "A2",
                "devices": [
                  "knk-1",
                  "scale-1"
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new session and the set_session outcome per device.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MeasurementSessionOpened"
                },
                "example": {
                  "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "tenant": "coop-dl",
                  "lot": "LO-260928-014",
                  "facility": "VN-TGPH-021",
                  "line": "A2",
                  "status": "open",
                  "opened_by": "operator@coop.example",
                  "opened_at": 1790000000.5,
                  "paused_at": null,
                  "closed_at": null,
                  "updated_at": 1790000000.5,
                  "devices": [
                    "knk-1",
                    "scale-1"
                  ],
                  "commands": [
                    {
                      "device_id": "knk-1",
                      "command_id": "9d2e7f40-1c3b-4a5e-8f6d-0b7c2a9e4d18",
                      "status": "sent",
                      "reason": null
                    },
                    {
                      "device_id": "scale-1",
                      "command_id": null,
                      "status": "skipped",
                      "reason": "not_declared"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad line, a bad device list, a device that is not an active device of the lot's facility, no device list while more than 16 devices of the facility declare set_session, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_line": {
                    "value": {
                      "error": "invalid line: 1 to 16 upper-case letters, digits or '-', starting with a letter or digit",
                      "code": "invalid_line"
                    }
                  },
                  "invalid_devices": {
                    "value": {
                      "error": "invalid devices: at most 16 distinct device ids",
                      "code": "invalid_devices"
                    }
                  },
                  "unknown_device": {
                    "value": {
                      "error": "unknown device",
                      "code": "unknown_device"
                    }
                  },
                  "too_many_devices": {
                    "value": {
                      "error": "too many devices: more than 16 devices of the facility declare set_session; send an explicit devices list",
                      "code": "too_many_devices"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot is closed or was sampled, the line already has an open or paused session, or a chosen device is in one. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_closed": {
                    "value": {
                      "error": "lot is closed",
                      "code": "lot_is_closed"
                    }
                  },
                  "line_busy": {
                    "value": {
                      "error": "line busy",
                      "code": "line_busy"
                    }
                  },
                  "device_busy": {
                    "value": {
                      "error": "device busy: knk-1",
                      "code": "device_busy"
                    }
                  },
                  "lot_sampled": {
                    "value": {
                      "error": "lot sampled: its export population is final",
                      "code": "lot_sampled"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/summary": {
      "get": {
        "operationId": "getLotSummary",
        "summary": "Lot summary",
        "description": "What the lot holds so far (man1 'lot so far'), aggregated over its fruit records: `count` fruits with a device record (status recorded or overridden, or rejected with a bound device envelope; `awaiting_device` and `rejected_unmeasured`, rejected before any measurement, apart), `kg` from the scale (rounded to 3 decimals) over the `weighed` ones, counts per effective ripeness level (the sensory level when overridden), per grade (a rejected fruit is a reject whatever its grade), sensory overrides, the mean device confidence, fruits pending review, what is exportable (A or B, not rejected) and the volume headroom of the lot's growing area for the season of its harvest date (null without a growing area). Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's summary.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotSummary"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "status": "open",
                  "count": 128,
                  "awaiting_device": 0,
                  "rejected_unmeasured": 0,
                  "kg": 364.2,
                  "weighed": 123,
                  "levels": {
                    "1": 7,
                    "2": 38,
                    "3": 78,
                    "4": 5,
                    "unknown": 0
                  },
                  "grades": {
                    "A": 96,
                    "B": 27,
                    "reject": 5,
                    "ungraded": 0
                  },
                  "overrides": 3,
                  "avg_confidence": 0.8884,
                  "pending_review": 0,
                  "export": {
                    "count": 123,
                    "kg": 364.2
                  },
                  "volume": {
                    "growing_area": "VN-TGOR-0387",
                    "season": "2026",
                    "declared_kg": 760.0,
                    "cap_kg": 2000.0,
                    "headroom_kg": 1240.0
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/applications": {
      "get": {
        "operationId": "listLotApplications",
        "summary": "Application records in the lot history",
        "description": "#241: the company's application records (`apply` events: water, fertiliser, pesticide, lime or light) on the lot's growing area during the season before its harvest, oldest first: dated from the longest pre-harvest interval a record may state after the longest application (365 days and one day) before the lot's harvest day (00:00 Asia/Ho_Chi_Minh) up to the end of that day, so every record whose interval could still be open at a harvest that day. The harvest day is the lot's harvest date, else the date of its harvest record, else the date the lot was created. Accepted and held (quarantined) records are listed; a record rejected after review is not. At most the 200 nearest the harvest, still oldest first (`more` says older ones were left out). A record entered by hand in the harvest app (`harvest_app`) is Self-declared. A lot without a growing area lists none. #322: `sprays` lists the spray records of the growing area's spray log (the console's spray records, as `GET /v1/growing-areas/{code}/sprays` and the public fruit record read them) sprayed from the first day of the same period to the harvest day, with their withholding status at the harvest day, so the lot's inputs and its growing area's spray log agree; they are listed only and hold no harvest. Staff only: the public record does not show them. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's application records.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotApplications"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "growing_area": "VN-TGOR-0387",
                  "from": "2025-09-25T17:00:00Z",
                  "until": "2026-09-27T17:00:00Z",
                  "items": [
                    {
                      "id": "7c0e9a52-4f1b-4d8e-9b0a-2f6c3d1e5a77",
                      "applied_at": "2026-09-10T00:30:00Z",
                      "input": "pesticide",
                      "product": {
                        "id": "VN-REG-0001",
                        "batch": "B-7",
                        "name": null
                      },
                      "product_mass_kg": null,
                      "product_volume_l": 1.5,
                      "duration_s": null,
                      "phi_days": 14,
                      "interval_ends_at": "2026-09-24T00:30:00Z",
                      "status": "accepted",
                      "reasons": [],
                      "device_id": "harvest-761ccd0930ffbe627fbe6d72",
                      "operator": "op-7",
                      "harvest_app": true
                    }
                  ],
                  "more": false,
                  "sprays": [
                    {
                      "id": 3,
                      "sprayed_on": "2026-09-01",
                      "product": "Ridomil Gold",
                      "active_ingredient": "metalaxyl-M",
                      "withholding_days": 14,
                      "safe_from": "2026-09-15",
                      "withholding_status": "ok"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/public/fruits/{publicId}": {
      "get": {
        "operationId": "getPublicFruit",
        "summary": "Public fruit record (and the scan of the web server's own read)",
        "description": "The public fruit page (man3), anonymous and tenant-less: no session, bearer token, cookie, CSRF token or X-Tenant is needed, and a request carrying any of them gets exactly the anonymous answer. Built from an explicit allowlist (the frontend's publicFruitSchema at waveX-c1-public-contract, mirrored as PublicFruit): no tenant, internal id, operator, line, envelope, IP data, coordinate or polygon; the grower's name only with public-display consent. A fruit is public when its lot is public (open or closed, see getPublicLot), its status is recorded or overridden (owner decision D4: awaiting_device, rejected and re-measured fruits are 404), its lot has a growing area and its measurement has every non-null field. The trust tier is min(lot tier, the fruit's own record tier), derived at read time; a sensory override demotes the record to Self-declared; an open hold (the lot's, or the fruit's own quarantined envelope) makes `status` `on_hold` with the capped tier; an open public report on any fruit of the lot (#46) holds the lot too, and while it is the only hold open `status` is `under_review`, with the capped tier. `report.url` is where a report is filed (POST /v1/public/reports). `trust.signature` is the knock envelope's signature as hex, re-verified against the registered key. Scans (owner decision D3): only a request carrying `X-Agritrace-Scan-Key` equal to the backend's AGRITRACE_PUBLIC_SCAN_KEY (the web server's own render) logs a scan; only then are its forwarded `cf-ipcountry`, `cf-region`, `cf-ipcity`, `cf-connecting-ip` and `user-agent` read (bounded; the address is stored only as an HMAC under a daily salt deleted after the day), `scan` is returned and the response is `private, no-store`. Any other request gets `scan: null`, writes nothing and is cacheable. More than 3 distinct scan places of one fruit open a `label_clone_suspected` alert (`report.scan_threshold`). There is no scan POST. Not audited (a read; a scan row is data). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second).",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The fruit's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "73879f17d0930440809333f141385eb6"
          },
          {
            "name": "lang",
            "in": "query",
            "required": false,
            "description": "Page language; absent means `vi`. Anything else (unknown, empty, repeated) is 400.",
            "schema": {
              "type": "string",
              "enum": [
                "vi",
                "zh-Hans",
                "en"
              ]
            },
            "example": "vi"
          },
          {
            "name": "trust_limits",
            "in": "query",
            "required": false,
            "description": "#280: `1` adds the record's `trust.limited_by` (the public pages ask for it); `0` or none leaves it out; any other value is refused (400 `bad trust_limits`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          },
          {
            "name": "map",
            "in": "query",
            "required": false,
            "description": "#293: `1` adds the record's commune map (`origin.map`, the public pages ask for it); `0` or none leaves it out; any other value is refused (400 `bad map`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          },
          {
            "name": "X-Agritrace-Scan-Key",
            "in": "header",
            "required": false,
            "description": "Internal scan key, sent only by the web server (D3): its read for the page's scan call (#177) and its read for the page itself. Equal to the configured key: the read logs a scan and trusts the forwarded cf-ipcountry, cf-region, cf-ipcity, cf-connecting-ip and user-agent headers, unless `X-Agritrace-No-Scan: 1` is sent too. Absent or different: those headers are ignored and nothing is written.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "X-Agritrace-No-Scan",
            "in": "header",
            "required": false,
            "description": "#177: sent as exactly `1` with the scan key by the web server's read for the page itself, which the edge may cache: the read is keyed for the per-visitor rate limit only, logs nothing, answers `scan: null` and is cacheable. Any other value, or without the key: no effect.",
            "schema": {
              "type": "string",
              "enum": [
                "1"
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The fruit's public record.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate); `private, no-store` when this read logged a scan (the internal scan key was sent without `X-Agritrace-No-Scan: 1`). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicFruit"
                },
                "example": {
                  "status": "normal",
                  "status_since": null,
                  "status_reason": null,
                  "public_id": "73879f17d0930440809333f141385eb6",
                  "code": "Q-001-0002",
                  "crop": "durian",
                  "variety": "Ri6",
                  "harvested_on": "2026-09-27",
                  "harvest_place": "Ngũ Hiệp, Cai Lậy, Tiền Giang, Việt Nam",
                  "carton_no": null,
                  "lot": {
                    "public_id": "758b25cfec067a59db94fea0fc7f0202",
                    "code": "LO-260928-014"
                  },
                  "trust": {
                    "tier": "self_declared",
                    "signature": {
                      "status": "valid",
                      "value": "7c98aba0eab54ab76083f43f371951b8be60826a1d860a67d77a387fe432fb0b263aae3631f218b70d247ed1cf5266e57234ecc90cbf84546d31006fa7e3f3bd"
                    }
                  },
                  "scan": {
                    "scan_number": 2,
                    "scanned_on": "2026-09-28",
                    "city": "Nanning",
                    "region": "Guangxi",
                    "days_since_harvest": 1
                  },
                  "measurement": {
                    "measured_at": "2026-09-28T08:56:00+07:00",
                    "device": {
                      "model": "SF-100",
                      "serial": "0417"
                    },
                    "ripeness_level": 3,
                    "model_confidence": 0.88,
                    "weight_kg": 2.94,
                    "grade": "A",
                    "eating_window": {
                      "start": "2026-10-01",
                      "end": "2026-10-02"
                    },
                    "waveform_peaks": null
                  },
                  "origin": {
                    "growing_area": {
                      "code": "VN-TGOR-0387",
                      "area_ha": 4.2,
                      "tree_count": 610
                    },
                    "grower": {
                      "name": null,
                      "organization": "HTX Ngũ Hiệp"
                    },
                    "orchard_position": null,
                    "tree_age_years": 9,
                    "last_spray": {
                      "applied_on": "2026-09-02",
                      "withholding_days": 25
                    },
                    "certification": {
                      "scheme": "VietGAP",
                      "status": "valid"
                    },
                    "satellite": {
                      "source": "Sentinel-2",
                      "image_date": "2026-09-25",
                      "area_matches_registration": true,
                      "deforestation_detected": false,
                      "image_url": null
                    }
                  },
                  "journey": [
                    {
                      "kind": "harvest",
                      "period": {
                        "precision": "day",
                        "start": "2026-09-27",
                        "end": null
                      },
                      "tier": "cross_checked",
                      "source": "registered_app",
                      "device_approval": {
                        "approved": true,
                        "approved_on": "2026-09-20"
                      }
                    },
                    {
                      "kind": "measurement",
                      "period": {
                        "precision": "minute",
                        "start": "2026-09-28T08:56:00+07:00",
                        "end": null
                      },
                      "tier": "device_recorded",
                      "source": "device",
                      "facility": {
                        "code": "VN-TGPH-021",
                        "name": "Tân Phú"
                      },
                      "device_model": "SF-100",
                      "device_approval": {
                        "approved": true,
                        "approved_on": "2026-09-20"
                      }
                    }
                  ],
                  "downloads": {
                    "epcis_url": null,
                    "credential_url": null
                  },
                  "report": {
                    "scan_threshold": 3,
                    "url": null
                  }
                }
              }
            }
          },
          "400": {
            "description": "`lang` is not one of vi, zh-Hans, en, or `map` is not 0 or 1 (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` on `bad lang` and `bad map`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lang": {
                    "value": {
                      "error": "bad lang",
                      "code": "bad_lang"
                    }
                  },
                  "requestId": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "map": {
                    "value": {
                      "error": "bad map",
                      "code": "bad_map"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "`lang` is not one of vi, zh-Hans, en (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                },
                "Cache-Control": {
                  "description": "`no-store` on `bad lang`.",
                  "schema": {
                    "type": "string"
                  }
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "lang": {
                      "value": {
                        "error": "bad lang",
                        "code": "bad_lang"
                      }
                    },
                    "requestId": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Not a public fruit: an unknown or malformed id, a fruit that is not recorded or overridden, a fruit of a lot that is not public or has no growing area, or one lacking a field the record needs. Every such id gets this same body (`not_found`) and headers, logs no scan, and is never echoed. One exception (D27, #322): a fruit taken out at grading (status rejected) of a public lot answers `fruit_rejected`, so the page its label opens can say the fruit was rejected at grading instead of naming no record; that body says nothing else about the fruit or its lot, the headers are the same, no scan is logged, and every other route of the fruit (credential, corrections, recording) answers the uniform `not_found`.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "notFound": {
                    "value": {
                      "error": "not found: fruits",
                      "code": "not_found"
                    }
                  },
                  "rejected": {
                    "value": {
                      "error": "fruit rejected: this fruit was taken out at grading and has no public record",
                      "code": "fruit_rejected"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "Not a public fruit: an unknown or malformed id, a fruit that is not recorded or overridden, a fruit of a lot that is not public or has no growing area, or one lacking a field the record needs. Every such id gets this same body and headers, logs no scan, and is never echoed.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                },
                "Cache-Control": {
                  "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                  "schema": {
                    "type": "string"
                  }
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "example": {
                    "error": "not found: fruits",
                    "code": "not_found"
                  }
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/resolve": {
      "get": {
        "operationId": "resolvePublicCode",
        "summary": "Resolve a scanned or typed code to its public lot or fruit record",
        "description": "The scan page's lookup (#139), anonymous and tenant-less like the public records: a request carrying a session, token, cookie or X-Tenant gets exactly the anonymous answer. `code` is the text a QR code or barcode decoded to, or that a visitor typed. Accepted (ADR 0004): our record URLs `/{vi|zh|en}/l/{publicId}` (lot) and `/{vi|zh|en}/q/{publicId}` (fruit, or a carton label: its lot), also without the locale segment, on the resolver origin (the deployment's AGRITRACE_RESOLVER_BASE, default https://txng.theio.vn) or AGRITRACE_PUBLIC_ORIGIN, with or without the scheme, or as a relative path; GS1 Digital Link URIs `/01/{gtin}/10/{lot}/21/{serial}` on those origins or id.gs1.org (the fruit, or the carton's lot, the serial names); GS1 element strings `(01)…(10)…(21)…` and raw scanner data (symbology identifier, GS-separated fields; AIs 11, 12, 13, 15, 16 and 17 are skipped); and a bare 32-hex public id. A GTIN may have 8, 12, 13 or 14 digits and needs a valid check digit. Never resolved: the codes printed for people (fruit `Q-…`, carton `C-…` and lot codes), which are sequential within a tenant; a GTIN and lot code without a serial, in any of the forms above, which no label prints and which would list a GTIN's lots by their guessable codes. Only a record the public pages show is answered (a public lot, a public fruit); everything else is the same 404, the code never echoed. Each request takes a token from the /v1/public/* bucket and from its own harder per-client bucket (bursts of 60, then 30 a minute).",
        "x-sdk-description": "The scan page's lookup (#139), anonymous and tenant-less like the public records: a request carrying a session, token, cookie or X-Tenant gets exactly the anonymous answer. `code` is the text a QR code or barcode decoded to, or that a visitor typed. Accepted (ADR 0004): our record URLs `/{vi|zh|en}/l/{publicId}` (lot) and `/{vi|zh|en}/q/{publicId}` (fruit, or a carton label: its lot), also without the locale segment, on the resolver origin (https://txng.theio.vn) or AGRITRACE_PUBLIC_ORIGIN, with or without the scheme, or as a relative path; GS1 Digital Link URIs `/01/{gtin}/10/{lot}/21/{serial}` on those origins or id.gs1.org (the fruit, or the carton's lot, the serial names); GS1 element strings `(01)…(10)…(21)…` and raw scanner data (symbology identifier, GS-separated fields; AIs 11, 12, 13, 15, 16 and 17 are skipped); and a bare 32-hex public id. A GTIN may have 8, 12, 13 or 14 digits and needs a valid check digit. Never resolved: the codes printed for people (fruit `Q-…`, carton `C-…` and lot codes), which are sequential within a tenant; a GTIN and lot code without a serial, in any of the forms above, which no label prints and which would list a GTIN's lots by their guessable codes. Only a record the public pages show is answered (a public lot, a public fruit); everything else is the same 404, the code never echoed. Each request takes a token from the /v1/public/* bucket and from its own harder per-client bucket (bursts of 60, then 30 a minute).",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "code",
            "in": "query",
            "required": true,
            "description": "The decoded or typed text, sent once, 1 to 512 characters (surrounding whitespace is ignored). Missing, empty, repeated or longer is 400.",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 512
            },
            "example": "https://txng.theio.vn/q/73879f17d0930440809333f141385eb6"
          }
        ],
        "responses": {
          "200": {
            "description": "The public record the code names.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicResolution"
                },
                "example": {
                  "kind": "fruit",
                  "public_id": "73879f17d0930440809333f141385eb6",
                  "locale_hint": null
                }
              }
            }
          },
          "400": {
            "description": "`code` is missing, empty, repeated or longer than 512 characters (`Cache-Control: no-store`; the code is never echoed), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` on `bad code`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "code": {
                    "value": {
                      "error": "bad code",
                      "code": "bad_code"
                    }
                  },
                  "requestId": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The code names no public record: an unknown, malformed or foreign code, a printed human code, a hidden lot or fruit, or a GS1 key without a serial. Every such code gets this same body and headers; the code is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: codes",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many requests from this client address: the /v1/public/* bucket (bursts of 60, then 20 a second) or the resolve bucket (bursts of 60, then 30 a minute). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer. Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/linkset": {
      "get": {
        "operationId": "getPublicLinkset",
        "summary": "Identity Resolver link set of a scanned or typed code",
        "description": "#162: the UNTP Identity Resolver answer (UNTP 0.7.0) for a code: an IETF link set (RFC 9264, `application/linkset+json`) of the public record the code names, decided exactly as GET /v1/public/resolve decides it (the same accepted forms: our record URLs `/l/{publicId}` and `/q/{publicId}` with or without a locale, GS1 Digital Link URIs `/01/{gtin}/10/{lot}[/21/{serial}]` (the serial-less lot key once the lot is sealed), GS1 element strings and a bare public id; the same enumeration rules, the same 404 and the same 410). A lot's context (anchor `https://<domain>/l/{publicId}`, the id its passport gives the product) lists its UNTP passport (`dpp`), the packing facility's record (`dfr`), the lab's conformity credential (`dcc`), its EPCIS document (`https://gs1.org/voc/traceability`) and its public page in each language (`https://gs1.org/voc/pip`, `hreflang` vi, en, zh), each only while its download answers. A fruit's code answers the fruit's context (anchor `https://<domain>/q/{publicId}`: its passport and pages) and then its lot's; a carton's code answers its lot's. The printed label URLs `https://<domain>/l/{publicId}`, `/q/{publicId}` and the GS1 Digital Links answer this link set too when asked for `application/linkset+json` (the `Accept` header) or with `?linkType=linkset` (or `all`); otherwise they redirect to the public page (/developers/downloads/verify.md). Anonymous and tenant-less: a request carrying a session, token, cookie or X-Tenant gets exactly the anonymous answer. Each request takes a token from the /v1/public/* bucket and from the resolve bucket (bursts of 60, then 30 a minute). Bounded work: the resolver's indexed lookups, then at most five indexed statements; no document is read, decoded or signed. Cross-origin readable (`Access-Control-Allow-Origin: *`). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "code",
            "in": "query",
            "required": true,
            "description": "The decoded or typed text, sent once, 1 to 512 characters (surrounding whitespace is ignored). Missing, empty, repeated or longer is 400.",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 512
            },
            "example": "https://txng.theio.vn/q/73879f17d0930440809333f141385eb6"
          }
        ],
        "responses": {
          "200": {
            "description": "The link set of the public record the code names.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/linkset+json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicLinkset"
                },
                "example": {
                  "linkset": [
                    {
                      "anchor": "https://txng.theio.vn/l/d806aa6d966385ff9a4ff78d53714356",
                      "dpp": [
                        {
                          "href": "https://txng.theio.vn/v1/public/lots/d806aa6d966385ff9a4ff78d53714356/credential",
                          "title": "UNTP Digital Product Passport of the lot",
                          "type": "application/vc+jwt"
                        }
                      ],
                      "dfr": [
                        {
                          "href": "https://txng.theio.vn/v1/public/lots/d806aa6d966385ff9a4ff78d53714356/facility-record",
                          "title": "UNTP Digital Facility Record of the packing facility",
                          "type": "application/vc+jwt"
                        }
                      ],
                      "https://gs1.org/voc/traceability": [
                        {
                          "href": "https://txng.theio.vn/v1/public/lots/d806aa6d966385ff9a4ff78d53714356/epcis.jsonld",
                          "title": "EPCIS 2.0 events of the lot",
                          "type": "application/ld+json"
                        }
                      ],
                      "https://gs1.org/voc/pip": [
                        {
                          "href": "https://txng.theio.vn/vi/l/d806aa6d966385ff9a4ff78d53714356",
                          "title": "Public lot record",
                          "type": "text/html",
                          "hreflang": [
                            "vi"
                          ]
                        },
                        {
                          "href": "https://txng.theio.vn/en/l/d806aa6d966385ff9a4ff78d53714356",
                          "title": "Public lot record",
                          "type": "text/html",
                          "hreflang": [
                            "en"
                          ]
                        },
                        {
                          "href": "https://txng.theio.vn/zh/l/d806aa6d966385ff9a4ff78d53714356",
                          "title": "Public lot record",
                          "type": "text/html",
                          "hreflang": [
                            "zh"
                          ]
                        }
                      ]
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "`code` is missing, empty, repeated or longer than 512 characters (`Cache-Control: no-store`; the code is never echoed), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` on `bad code`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "code": {
                    "value": {
                      "error": "bad code",
                      "code": "bad_code"
                    }
                  },
                  "requestId": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The code names no public record: an unknown, malformed or foreign code, a printed human code, a hidden lot or fruit, or a GS1 key without a serial. Every such code gets this same body and headers; the code is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: codes",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many requests from this client address: the /v1/public/* bucket (bursts of 60, then 20 a second) or the resolve bucket (bursts of 60, then 30 a minute). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer. Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/public/lots/{publicId}": {
      "get": {
        "operationId": "getPublicLot",
        "summary": "Public lot record and verification summary",
        "description": "The public lot page (man2), anonymous and tenant-less: no session, bearer token, cookie, CSRF token or X-Tenant is needed, and a request carrying any of them gets exactly the anonymous answer. Built from an explicit allowlist (the frontend's publicLotSchema at waveX-c1-public-contract, mirrored as PublicLot): no tenant, internal id, operator, line, envelope, IP data, grower name, coordinate or polygon. A lot is public when its status is open or closed, its product is a crop of the crop registry (#156; durian until a platform admin adds another) and it has a variety and a harvest date (owner decision D2). Display strings are stored in one language and returned as stored for every `lang`; `origin_country` is localised (D5). The trust tier is derived at read time (trust.py, never stored); an open hold (a lot fruit bound to a quarantined envelope, a key revoked for compromise that signed one of the lot's accepted envelopes, or a failing lab result (P4, #40)) makes `status` `on_hold` with the capped tier; an open public report on one of its fruits (#46, POST /v1/public/reports) holds it too, and while it is the only hold open `status` is `under_review`, with the capped tier. `verification.signed_event_count` counts the lot's accepted envelopes whose signature re-verifies against the registered key (cached per lot until its accepted-envelope count changes; at most 128 envelopes are re-verified per request, so a larger lot reports the count verified so far until it completes); `signatures` is `invalid` when one fails. #329: an answer whose re-verification does not cover every accepted envelope yet says so in `verification.signatures_complete` (false; only with `signatures_complete=1`) and is `Cache-Control: private, no-store`, so a shared cache only ever keeps a complete count. Fields without a source yet are null (D1): cartons, packing date, export, downloads; `issuer` (the self-check box) is null until X3 publishes the lot's credential, also for a lot sealed by L10 (#35), whose credential is not public; `lab` is null until the lab's signed report exists (P4, #40: one row per analyte, the highest measured value over the samples, the market limit and the verdict; the journey's lab step and `trust.tested_analytes` with it). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second).",
        "x-sdk-description": "The public lot page (man2), anonymous and tenant-less: no session, bearer token, cookie, CSRF token or X-Tenant is needed, and a request carrying any of them gets exactly the anonymous answer. Built from an explicit allowlist (the frontend's publicLotSchema at waveX-c1-public-contract, mirrored as PublicLot): no tenant, internal id, operator, line, envelope, IP data, grower name, coordinate or polygon. A lot is public when its status is open or closed, its product is durian and it has a variety and a harvest date (owner decision D2). Display strings are stored in one language and returned as stored for every `lang`; `origin_country` is localised (D5). The trust tier is derived at read time (trust.py, never stored); an open hold (a lot fruit bound to a quarantined envelope, a key revoked for compromise that signed one of the lot's accepted envelopes, or a failing lab result (P4, #40)) makes `status` `on_hold` with the capped tier; an open public report on one of its fruits (#46, POST /v1/public/reports) holds it too, and while it is the only hold open `status` is `under_review`, with the capped tier. `verification.signed_event_count` counts the lot's accepted envelopes whose signature re-verifies against the registered key (cached per lot until its accepted-envelope count changes; at most 128 envelopes are re-verified per request, so a larger lot reports the count verified so far until it completes); `signatures` is `invalid` when one fails. Fields without a source yet are null (D1): cartons, packing date, export, downloads; `issuer` (the self-check box) is null until X3 publishes the lot's credential, also for a lot sealed by L10 (#35), whose credential is not public; `lab` is null until the lab's signed report exists (P4, #40: one row per analyte, the highest measured value over the samples, the market limit and the verdict; the journey's lab step and `trust.tested_analytes` with it). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second).",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          },
          {
            "name": "lang",
            "in": "query",
            "required": false,
            "description": "Page language; absent means `vi`. Anything else (unknown, empty, repeated) is 400.",
            "schema": {
              "type": "string",
              "enum": [
                "vi",
                "zh-Hans",
                "en"
              ]
            },
            "example": "vi"
          },
          {
            "name": "crop_profile",
            "in": "query",
            "required": false,
            "description": "#156: `1` adds the lot's `crop_name` and `ripeness_scale` (the public pages ask for them); `0` or none leaves them out; any other value is refused (400 `bad crop_profile`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          },
          {
            "name": "trust_limits",
            "in": "query",
            "required": false,
            "description": "#280: `1` adds the record's `trust.limited_by` (the public pages ask for it); `0` or none leaves it out; any other value is refused (400 `bad trust_limits`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          },
          {
            "name": "map",
            "in": "query",
            "required": false,
            "description": "#293: `1` adds the record's commune map (`growing_area.map`, the public pages ask for it); `0` or none leaves it out; any other value is refused (400 `bad map`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          },
          {
            "name": "signatures_complete",
            "in": "query",
            "required": false,
            "description": "#329: `1` adds `verification.signatures_complete`, whether `signed_event_count` and `signatures` cover every accepted event of the lot yet (the public lot page asks for it); `0` or none leaves it out; any other value is refused (400 `bad signatures_complete`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's public record.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). #329: `private, no-store` while the signature re-verification does not cover every accepted envelope yet (`verification.signatures_complete` false), so no shared cache keeps a count that is still growing. Never `Set-Cookie`.",
                "x-sdk-description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicLot"
                },
                "example": {
                  "status": "normal",
                  "status_since": null,
                  "status_reason": null,
                  "public_id": "074eb09b371fc71c380da235aea9c14a",
                  "code": "LO-260928-014",
                  "crop": "durian",
                  "crop_name": "Sầu riêng",
                  "ripeness_scale": "levels_1_to_4",
                  "variety": "Ri6",
                  "origin_country": "Việt Nam",
                  "fruit_count": 5,
                  "net_mass_kg": 14.41,
                  "carton_count": null,
                  "packed_on": null,
                  "harvested_on": "2026-09-27",
                  "facility": {
                    "code": "VN-TGPH-021",
                    "name": "Tân Phú",
                    "locality": "Cai Lậy, Tiền Giang"
                  },
                  "growing_area": {
                    "code": "VN-TGOR-0387",
                    "locality": "Ngũ Hiệp, Cai Lậy",
                    "area_ha": 4.2,
                    "tree_count": 610
                  },
                  "export": null,
                  "trust": {
                    "tier": "self_declared",
                    "tested_analytes": []
                  },
                  "verification": {
                    "signed_event_count": 13,
                    "signatures": "valid",
                    "timestamp": {
                      "status": "missing"
                    },
                    "duplicate_scans": false,
                    "seal": {
                      "signature": "valid",
                      "sealed_at": "2026-09-30T14:40:00+07:00",
                      "manifest_sha256": "a869373f50f23727be3ef525863a48347c2c7d057119b62e02076adaa472d617"
                    }
                  },
                  "journey": [
                    {
                      "kind": "harvest",
                      "period": {
                        "precision": "day",
                        "start": "2026-09-27",
                        "end": null
                      },
                      "tier": "cross_checked",
                      "source": "registered_app",
                      "harvest_mass_kg": 500.0,
                      "satellite": {
                        "source": "Sentinel-2",
                        "image_date": "2026-09-25",
                        "area_matches_registration": true,
                        "deforestation_detected": false
                      },
                      "device_approval": {
                        "approved": true,
                        "approved_on": "2026-09-20"
                      }
                    },
                    {
                      "kind": "measurement",
                      "period": {
                        "precision": "minute",
                        "start": "2026-09-28T08:54:00+07:00",
                        "end": "2026-09-28T09:26:00+07:00"
                      },
                      "tier": "cross_checked",
                      "source": "device",
                      "device": {
                        "model": "SF-100",
                        "serial": "0417",
                        "model_version": "sf100-m3"
                      },
                      "measured_count": 6,
                      "rejected_count": 1,
                      "device_approval": {
                        "approved": true,
                        "approved_on": "2026-09-20"
                      }
                    }
                  ],
                  "ripeness": {
                    "exported_count": 5,
                    "device_model": "SF-100",
                    "counts": {
                      "1": 0,
                      "2": 2,
                      "3": 3,
                      "4": 0
                    },
                    "majority_level": 3,
                    "eating_window": {
                      "start": "2026-10-01",
                      "end": "2026-10-02"
                    },
                    "storage_temperature_c": null,
                    "mean_confidence": 0.91,
                    "calibrated_on": "2026-09-15",
                    "override_count": 1
                  },
                  "lab": null,
                  "downloads": {
                    "epcis_url": null,
                    "credential_url": null,
                    "customs_dossier_url": null
                  },
                  "issuer": null
                },
                "x-sdk-example": {
                  "status": "normal",
                  "status_since": null,
                  "status_reason": null,
                  "public_id": "074eb09b371fc71c380da235aea9c14a",
                  "code": "LO-260928-014",
                  "crop": "durian",
                  "variety": "Ri6",
                  "origin_country": "Việt Nam",
                  "fruit_count": 5,
                  "net_mass_kg": 14.41,
                  "carton_count": null,
                  "packed_on": null,
                  "harvested_on": "2026-09-27",
                  "facility": {
                    "code": "VN-TGPH-021",
                    "name": "Tân Phú",
                    "locality": "Cai Lậy, Tiền Giang"
                  },
                  "growing_area": {
                    "code": "VN-TGOR-0387",
                    "locality": "Ngũ Hiệp, Cai Lậy",
                    "area_ha": 4.2,
                    "tree_count": 610
                  },
                  "export": null,
                  "trust": {
                    "tier": "self_declared",
                    "tested_analytes": []
                  },
                  "verification": {
                    "signed_event_count": 13,
                    "signatures": "valid",
                    "timestamp": {
                      "status": "missing"
                    },
                    "duplicate_scans": false,
                    "seal": {
                      "signature": "valid",
                      "sealed_at": "2026-09-30T14:40:00+07:00",
                      "manifest_sha256": "a869373f50f23727be3ef525863a48347c2c7d057119b62e02076adaa472d617"
                    }
                  },
                  "journey": [
                    {
                      "kind": "harvest",
                      "period": {
                        "precision": "day",
                        "start": "2026-09-27",
                        "end": null
                      },
                      "tier": "cross_checked",
                      "source": "registered_app",
                      "harvest_mass_kg": 500.0,
                      "satellite": {
                        "source": "Sentinel-2",
                        "image_date": "2026-09-25",
                        "area_matches_registration": true,
                        "deforestation_detected": false
                      },
                      "device_approval": {
                        "approved": true,
                        "approved_on": "2026-09-20"
                      }
                    },
                    {
                      "kind": "measurement",
                      "period": {
                        "precision": "minute",
                        "start": "2026-09-28T08:54:00+07:00",
                        "end": "2026-09-28T09:26:00+07:00"
                      },
                      "tier": "cross_checked",
                      "source": "device",
                      "device": {
                        "model": "SF-100",
                        "serial": "0417",
                        "model_version": "sf100-m3"
                      },
                      "measured_count": 6,
                      "rejected_count": 1,
                      "device_approval": {
                        "approved": true,
                        "approved_on": "2026-09-20"
                      }
                    }
                  ],
                  "ripeness": {
                    "exported_count": 5,
                    "device_model": "SF-100",
                    "counts": {
                      "1": 0,
                      "2": 2,
                      "3": 3,
                      "4": 0
                    },
                    "majority_level": 3,
                    "eating_window": {
                      "start": "2026-10-01",
                      "end": "2026-10-02"
                    },
                    "storage_temperature_c": null,
                    "mean_confidence": 0.91,
                    "calibrated_on": "2026-09-15",
                    "override_count": 1
                  },
                  "lab": null,
                  "downloads": {
                    "epcis_url": null,
                    "credential_url": null,
                    "customs_dossier_url": null
                  },
                  "issuer": null
                }
              }
            }
          },
          "400": {
            "description": "`lang` is not one of vi, zh-Hans, en, or `crop_profile` is not 0 or 1, or `map` or `signatures_complete` is not 0 or 1 (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` on `bad lang`, `bad crop_profile`, `bad map` and `bad signatures_complete`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lang": {
                    "value": {
                      "error": "bad lang",
                      "code": "bad_lang"
                    }
                  },
                  "cropProfile": {
                    "value": {
                      "error": "bad crop_profile",
                      "code": "bad_crop_profile"
                    }
                  },
                  "requestId": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "map": {
                    "value": {
                      "error": "bad map",
                      "code": "bad_map"
                    }
                  },
                  "signaturesComplete": {
                    "value": {
                      "error": "bad signatures_complete",
                      "code": "bad_signatures_complete"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "`lang` is not one of vi, zh-Hans, en (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                },
                "Cache-Control": {
                  "description": "`no-store` on `bad lang`.",
                  "schema": {
                    "type": "string"
                  }
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "lang": {
                      "value": {
                        "error": "bad lang",
                        "code": "bad_lang"
                      }
                    },
                    "requestId": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Not a public lot: an unknown or malformed id, a lot that is not open or closed, not of a crop of the crop registry (#156), or lacks a field the record needs. Every such id gets this same body and headers; the id is never echoed.",
            "x-sdk-description": "Not a public lot: an unknown or malformed id, a lot that is not open or closed, not durian, or lacks a field the record needs. Every such id gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/lots/{publicId}/customs-dossier": {
      "get": {
        "operationId": "getPublicLotCustomsDossier",
        "summary": "Code file for China customs (JSON)",
        "description": "X4 (#45): the lot's code file for China customs (its customs dossier) as canonical JSON (PublicCustomsDossier), a download named `customs-dossier-<lot code>-<lang>.json`. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). The work is the public lot record's plus a projection of it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          },
          {
            "name": "lang",
            "in": "query",
            "required": false,
            "description": "Page language; absent means `vi`. Anything else (unknown, empty, repeated) is 400.",
            "schema": {
              "type": "string",
              "enum": [
                "vi",
                "zh-Hans",
                "en"
              ]
            },
            "example": "vi"
          }
        ],
        "responses": {
          "200": {
            "description": "The dossier: its RFC 8785 (JCS) form, the same bytes for the same stored facts.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"customs-dossier-<lot code>-<lang>.json\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicCustomsDossier"
                },
                "example": {
                  "format": "agritrace-customs-dossier/1",
                  "lang": "en",
                  "status": "normal",
                  "trust_tier": "self_declared",
                  "public_id": "074eb09b371fc71c380da235aea9c14a",
                  "origin_country": "Vietnam",
                  "sealed": {
                    "lot": {
                      "code": "LOT-0001",
                      "product": "durian",
                      "variety": "Ri6",
                      "harvested_on": "2026-09-27",
                      "packed_on": "2026-09-28"
                    },
                    "cartons": {
                      "count": 12,
                      "fruit_count": 96,
                      "net_mass_kg": 268.4
                    },
                    "growing_area": {
                      "code": "AREA-0001",
                      "commune": "Commune",
                      "district": "District"
                    },
                    "packing_house": {
                      "code": "PH-01",
                      "name": "Packing house",
                      "district": "District",
                      "province": "Province"
                    },
                    "durian_protocol": false
                  },
                  "seal": {
                    "algorithm": "sha-256",
                    "value": "b9b4c466fc0bedf26722ae773931d48cfb0807a8b1c5d7224c81bf32cfda024e",
                    "basis": "transition"
                  },
                  "registry_entry": {
                    "tier": "self_declared",
                    "source": "manual"
                  },
                  "lab_report": {
                    "report_number": "KN-0001",
                    "signed_at": "2026-09-29T15:40:00+07:00",
                    "key_custody": "lab",
                    "market_approval": {
                      "market": {
                        "country_code": "CN",
                        "short_name": "China",
                        "authority": "China Customs"
                      },
                      "approved": true,
                      "reference": "BVTV 50-2026 No. 17"
                    },
                    "results": [
                      {
                        "analyte": "cadmium",
                        "outcome": "measured",
                        "value": 0.018,
                        "unit": "mg/kg",
                        "limit": {
                          "kind": "max",
                          "value": 0.05
                        },
                        "pass": true
                      },
                      {
                        "analyte": "auramine_o",
                        "outcome": "not_detected",
                        "limit": {
                          "kind": "banned"
                        },
                        "pass": true
                      }
                    ]
                  },
                  "shipment": {
                    "market": {
                      "country_code": "CN",
                      "short_name": "China",
                      "authority": "China Customs"
                    },
                    "border_gate": "Border gate",
                    "exported_on": null
                  },
                  "protocol": null,
                  "producer": {
                    "legal_name": "Hợp tác xã Sầu riêng Ea Kly",
                    "address": "Thôn 2, xã Ea Kly",
                    "district": "Krông Pắc",
                    "province": "Đắk Lắk",
                    "country": "VN"
                  },
                  "digest": {
                    "algorithm": "sha-256",
                    "value": "889a1a4c2fe3d8a61826fe159b4f6e986219672d9c56952811fd6118e3cac6f5"
                  }
                }
              }
            }
          },
          "400": {
            "description": "`lang` is not one of vi, zh-Hans, en (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` on `bad lang`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lang": {
                    "value": {
                      "error": "bad lang",
                      "code": "bad_lang"
                    }
                  },
                  "requestId": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No dossier: every id the public lot route answers 404 for, and a public lot that is not packed or is on no shipment to the CN market. Every such id gets this same body and headers (the public lot's `not found: lots`); the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/lots/{publicId}/customs-dossier/print": {
      "get": {
        "operationId": "getPublicLotCustomsDossierPrint",
        "summary": "Code file for China customs (HTML print view)",
        "description": "X4 (#45): the same code file (dossier) as a static HTML page in `lang` to print or save, with a link to the JSON download. It runs no script and loads nothing (`Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; ...`); every value is HTML-escaped. The lot page's `downloads.customs_dossier_url` links here. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). The work is the public lot record's plus a projection of it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          },
          {
            "name": "lang",
            "in": "query",
            "required": false,
            "description": "Page language; absent means `vi`. Anything else (unknown, empty, repeated) is 400.",
            "schema": {
              "type": "string",
              "enum": [
                "vi",
                "zh-Hans",
                "en"
              ]
            },
            "example": "vi"
          }
        ],
        "responses": {
          "200": {
            "description": "The print view.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Security-Policy": {
                "description": "`default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`.",
                "schema": {
                  "type": "string"
                }
              },
              "Referrer-Policy": {
                "description": "`no-referrer`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                },
                "example": "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Code file for China Customs</title></head><body><main><h1>Code file for China Customs</h1>…</main></body></html>"
              }
            }
          },
          "400": {
            "description": "`lang` is not one of vi, zh-Hans, en (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` on `bad lang`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lang": {
                    "value": {
                      "error": "bad lang",
                      "code": "bad_lang"
                    }
                  },
                  "requestId": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No dossier: every id the public lot route answers 404 for, and a public lot that is not packed or is on no shipment to the CN market. Every such id gets this same body and headers (the public lot's `not found: lots`); the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/quarantine": {
      "get": {
        "operationId": "listQuarantine",
        "summary": "Envelopes held for review",
        "description": "Up to 200 quarantined envelopes of the tenant, oldest received first. Approve or reject each with the review route.",
        "tags": [
          "integrity"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "tenant_read"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "Quarantined envelopes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/QuarantinedEnvelope"
                  }
                },
                "example": [
                  {
                    "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
                    "device_id": "scale-1",
                    "seq": 3,
                    "kind": "event",
                    "event_type": "receive",
                    "event_time": "2026-09-30T08:00:00.000+07:00",
                    "lot": "LOT-A",
                    "growing_area": "VN-DL-SR-0123",
                    "reasons": [
                      "volume_exceeds_cap"
                    ]
                  }
                ]
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sessions/{id}": {
      "get": {
        "operationId": "getMeasurementSession",
        "summary": "One measurement session",
        "description": "A measurement session of the caller's tenant (not a login session). Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          }
        ],
        "responses": {
          "200": {
            "description": "The session.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MeasurementSession"
                },
                "example": {
                  "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "tenant": "coop-dl",
                  "lot": "LO-260928-014",
                  "facility": "VN-TGPH-021",
                  "line": "A2",
                  "status": "open",
                  "opened_by": "operator@coop.example",
                  "opened_at": 1790000000.5,
                  "paused_at": null,
                  "closed_at": null,
                  "updated_at": 1790000000.5,
                  "devices": [
                    "knk-1",
                    "scale-1"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sessions/{id}/close": {
      "post": {
        "operationId": "closeMeasurementSession",
        "summary": "Close a measurement session",
        "description": "open or paused -> closed. Sets closed_at and frees the line. Any other state is 409 invalid transition. Audited (`session.close`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The session after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MeasurementSession"
                },
                "example": {
                  "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "tenant": "coop-dl",
                  "lot": "LO-260928-014",
                  "facility": "VN-TGPH-021",
                  "line": "A2",
                  "status": "closed",
                  "opened_by": "operator@coop.example",
                  "opened_at": 1790000000.5,
                  "paused_at": null,
                  "closed_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "devices": [
                    "knk-1",
                    "scale-1"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The session is not in a state this action leaves. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_transition": {
                    "value": {
                      "error": "invalid transition: closed to closed",
                      "code": "invalid_transition"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sessions/{id}/feed": {
      "get": {
        "operationId": "getSessionFeed",
        "summary": "What changed on a measurement session after a cursor",
        "description": "The session's fruit upserts with an rx_seq above `after`, ascending (only this session's fruits; a fruit changed several times since `after` appears once, with its latest rx_seq), and a status snapshot: the session's status, the status read model of every device stored on the session, the scale live weight (the newest numeric `mass.net` reading among each session device's latest 32 stored envelopes of any kind) and the pending counts of the session's fruits. Poll it with `after = next_after` (the fallback when the stream answers 503). Not audited. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the sessions of its facilities); a lab is refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "name": "after",
            "in": "query",
            "required": false,
            "description": "Return the fruit upserts with an rx_seq above this one (`next_after` of the previous call); a decimal integer from 0 to 2^63-1.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 9223372036854775807,
              "default": 0
            },
            "example": 412
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "At most this many fruit upserts, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 100
            },
            "example": 100
          }
        ],
        "responses": {
          "200": {
            "description": "The fruit upserts after the cursor and the status snapshot.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SessionFeed"
                },
                "example": {
                  "items": [
                    {
                      "rx_seq": 413,
                      "fruit": {
                        "tenant": "coop-dl",
                        "code": "Q-014-0129",
                        "n": 129,
                        "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                        "lot": "LO-260928-014",
                        "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                        "line": "A2",
                        "operator": "user-7",
                        "status": "awaiting_device",
                        "labels_printed_at": 1790000000.5,
                        "created_at": 1790000000.5,
                        "updated_at": 1790000000.5,
                        "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                        "level": null,
                        "level_pred": null,
                        "maturity_class": null,
                        "confidence": null,
                        "model": null,
                        "measured_at": null,
                        "weight_kg": null,
                        "level_sensory": null,
                        "override": false,
                        "pending_review": false,
                        "grade": null,
                        "eating_window": null,
                        "record_tier": null,
                        "knock_envelope_id": null,
                        "scale_envelope_id": null,
                        "override_envelope_id": null
                      }
                    }
                  ],
                  "next_after": 413,
                  "session_status": "open",
                  "devices": [
                    {
                      "device_id": "knk-1",
                      "tenant": "coop-dl",
                      "site": "ph1",
                      "facility": "VN-TGPH-021",
                      "profile": "vn.agritrace.durian-knocker",
                      "status": "active",
                      "display_name": "Knocker line 1",
                      "vendor_model": "SF-100",
                      "serial": "SF100-000123",
                      "created_at": 1790000000.5,
                      "commands": [
                        "calibrate",
                        "set_model",
                        "set_session"
                      ],
                      "last_seen": 1790003600.25,
                      "max_seq": 412,
                      "last_model": "m1",
                      "firmware": "1.4.2",
                      "battery_pct": 87.0,
                      "battery_v": 3.92,
                      "last_calibrated_at": 1789990000.0,
                      "ready": true,
                      "approval": "approved",
                      "approval_reason": null,
                      "approval_at": 1790000100.0
                    }
                  ],
                  "scale": {
                    "device_id": "scl-st",
                    "weight_kg": 2.84,
                    "at": 1790003600.25
                  },
                  "pending": {
                    "awaiting_device": 1,
                    "pending_review": 0
                  }
                }
              }
            }
          },
          "400": {
            "description": "An `after` that is not an integer from 0 to 2^63-1, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sessions/{id}/fruits": {
      "get": {
        "operationId": "listSessionFruits",
        "summary": "Fruits of a measurement session",
        "description": "The session's fruits in allocation order (n ascending) with keyset pagination. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the sessions of its facilities).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJuIjoxMjh9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of fruits.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FruitPage"
                },
                "example": {
                  "items": [
                    {
                      "tenant": "coop-dl",
                      "code": "Q-014-0129",
                      "n": 129,
                      "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                      "lot": "LO-260928-014",
                      "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                      "line": "A2",
                      "operator": "user-7",
                      "status": "awaiting_device",
                      "labels_printed_at": 1790000000.5,
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5,
                      "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                      "level": null,
                      "level_pred": null,
                      "maturity_class": null,
                      "confidence": null,
                      "model": null,
                      "measured_at": null,
                      "weight_kg": null,
                      "level_sensory": null,
                      "override": false,
                      "pending_review": false,
                      "grade": null,
                      "eating_window": null,
                      "record_tier": null,
                      "knock_envelope_id": null,
                      "scale_envelope_id": null,
                      "override_envelope_id": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor this API did not issue, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "allocateFruit",
        "summary": "Allocate the next fruit of a measurement session",
        "description": "Allocates the next fruit of the session's lot: n is gap-free per lot across all of its sessions and the code is `Q-<lot seq, 3+ digits>-<n, 4+ digits>`. The label is printed now (`labels_printed_at`); the operator is the caller (`user-<id>` for a signed-in user, none for API tokens), never a body field. After the fruit is stored, `set_session {lot, fruit, line[, operator]}` goes to every device of the session whose profile declares it; a device without it is skipped and a transport failure is reported per device, neither undoes the fruit. Only an open session of a draft or open lot allocates. Audited (`fruit.allocate`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FruitAllocate"
              },
              "example": {}
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new fruit, its label payload and the set_session outcome per device.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FruitAllocated"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "Q-014-0129",
                  "n": 129,
                  "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                  "lot": "LO-260928-014",
                  "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "line": "A2",
                  "operator": "user-7",
                  "status": "awaiting_device",
                  "labels_printed_at": 1790000000.5,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                  "label": {
                    "code": "Q-014-0129",
                    "lot": "LO-260928-014",
                    "n": 129,
                    "line": "A2",
                    "operator": "user-7",
                    "printed_at": 1790000000.5,
                    "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
                  },
                  "commands": [
                    {
                      "device_id": "knk-1",
                      "command_id": "9d2e7f40-1c3b-4a5e-8f6d-0b7c2a9e4d18",
                      "status": "sent",
                      "reason": null
                    },
                    {
                      "device_id": "scale-1",
                      "command_id": "1a6b3c8d-2e4f-4a7b-9c0d-5e8f1a2b3c4d",
                      "status": "sent",
                      "reason": null
                    }
                  ],
                  "level": null,
                  "level_pred": null,
                  "maturity_class": null,
                  "confidence": null,
                  "model": null,
                  "measured_at": null,
                  "weight_kg": null,
                  "level_sensory": null,
                  "override": false,
                  "pending_review": false,
                  "grade": null,
                  "eating_window": null,
                  "record_tier": null,
                  "knock_envelope_id": null,
                  "scale_envelope_id": null,
                  "override_envelope_id": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not an object, any body field, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "not_an_object": {
                    "value": {
                      "error": "expected a JSON object",
                      "code": "expected_a_json_object"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The session's lot is past open, or the session is paused or closed. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_closed": {
                    "value": {
                      "error": "lot is closed",
                      "code": "lot_is_closed"
                    }
                  },
                  "session_paused": {
                    "value": {
                      "error": "session is paused",
                      "code": "session_is_paused"
                    }
                  },
                  "session_closed": {
                    "value": {
                      "error": "session is closed",
                      "code": "session_is_closed"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sessions/{id}/pause": {
      "post": {
        "operationId": "pauseMeasurementSession",
        "summary": "Pause a measurement session",
        "description": "open -> paused. Sets paused_at; the session keeps its line. Any other state is 409 invalid transition. Audited (`session.pause`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The session after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MeasurementSession"
                },
                "example": {
                  "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "tenant": "coop-dl",
                  "lot": "LO-260928-014",
                  "facility": "VN-TGPH-021",
                  "line": "A2",
                  "status": "paused",
                  "opened_by": "operator@coop.example",
                  "opened_at": 1790000000.5,
                  "paused_at": 1790000000.5,
                  "closed_at": null,
                  "updated_at": 1790000000.5,
                  "devices": [
                    "knk-1",
                    "scale-1"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The session is not in a state this action leaves. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_transition": {
                    "value": {
                      "error": "invalid transition: paused to paused",
                      "code": "invalid_transition"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sessions/{id}/resume": {
      "post": {
        "operationId": "resumeMeasurementSession",
        "summary": "Resume a measurement session",
        "description": "paused -> open. Any other state is 409 invalid transition. Audited (`session.resume`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The session after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MeasurementSession"
                },
                "example": {
                  "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "tenant": "coop-dl",
                  "lot": "LO-260928-014",
                  "facility": "VN-TGPH-021",
                  "line": "A2",
                  "status": "open",
                  "opened_by": "operator@coop.example",
                  "opened_at": 1790000000.5,
                  "paused_at": null,
                  "closed_at": null,
                  "updated_at": 1790000000.5,
                  "devices": [
                    "knk-1",
                    "scale-1"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The session is not in a state this action leaves. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_transition": {
                    "value": {
                      "error": "invalid transition: open to open",
                      "code": "invalid_transition"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sessions/{id}/stream": {
      "get": {
        "operationId": "streamSession",
        "summary": "Live server-sent events of a measurement session",
        "description": "A `text/event-stream` (no Content-Length; `Cache-Control: no-cache`, `X-Accel-Buffering: no`; the connection closes when the stream ends). It starts with `retry: 2000`, then sends every fruit upsert after the resume point as `id: <rx_seq>` / `event: fruit` / `data: {rx_seq, fruit}` in rx_seq order; `event: status` (no id, so it never moves the client's cursor) with `{session_status, devices, scale, pending}` (as in the feed) once at the start and whenever it changes; a `: hb` comment after 15 s without output; and, once the session is closed and its backlog sent, `event: end` with `{\"reason\": \"session_closed\"}`. The server polls once a second and ends a stream after its lifetime (30 minutes by default; the client reconnects with `Last-Event-ID`). The resume point is the `Last-Event-ID` header when sent, else `after`, else 0. At most 64 streams per backend process, at most half of them (32) for one tenant and at most 4 for one principal (a signed-in user or an API token): above any of these the answer is 503 with `Retry-After: 2` and the client polls the feed every 2 s. Authentication, the role check, the parameters and the session lookup are answered as JSON before any stream byte; the credential and the grant are checked again on every poll, so a logout, a revoked or expired session or API token, a disabled user, a password change or a grant that no longer covers the session ends the stream at once, without an `end` event (the reconnect is then refused). EventSource cannot send `X-Tenant`: a session principal streams its default tenant. Not audited. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the sessions of its facilities); a lab is refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "name": "Last-Event-ID",
            "in": "header",
            "required": false,
            "description": "The id of the last event received (sent by EventSource on reconnect): resume after this rx_seq; a decimal integer from 0 to 2^63-1. Takes precedence over `after`.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,19}$"
            },
            "example": "413"
          },
          {
            "name": "after",
            "in": "query",
            "required": false,
            "description": "Return the fruit upserts with an rx_seq above this one (`next_after` of the previous call); a decimal integer from 0 to 2^63-1.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 9223372036854775807,
              "default": 0
            },
            "example": 412
          }
        ],
        "responses": {
          "200": {
            "description": "The event stream.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Accel-Buffering": {
                "description": "`no`: proxies must not buffer the stream.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string"
                },
                "example": "retry: 2000\n\nid: 413\nevent: fruit\ndata: {\"rx_seq\":413,\"fruit\":{\"code\":\"Q-014-0129\",\"status\":\"recorded\"}}\n\nevent: status\ndata: {\"session_status\":\"open\",\"devices\":[],\"scale\":null,\"pending\":{\"awaiting_device\":0,\"pending_review\":0}}\n\n: hb\n\nevent: end\ndata: {\"reason\":\"session_closed\"}\n\n"
              }
            }
          },
          "400": {
            "description": "A malformed `Last-Event-ID` or `after`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_last_event_id": {
                    "value": {
                      "error": "bad last event id",
                      "code": "bad_last_event_id"
                    }
                  },
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "Too many concurrent streams on this backend process, for the caller's tenant or for the caller; poll the feed instead and retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many streams",
                  "code": "too_many_streams"
                }
              }
            }
          }
        }
      }
    },
    "/v1/tenants": {
      "get": {
        "operationId": "listTenants",
        "summary": "Every tenant",
        "description": "All tenants ordered by id, with keyset pagination. Allowed for platform_admin only.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of tenants.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IlZOLVRHUEgtMDIxIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "platform",
            "in": "query",
            "required": false,
            "description": "`1` adds `platform` to each company (#282); `0` or none leaves it out; any other value is refused (400 `bad platform`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "One page of tenants.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TenantPage"
                },
                "example": {
                  "items": [
                    {
                      "id": "coop-dl",
                      "name": "Dak Lak durian co-op",
                      "source": "manual",
                      "created_at": 1790000000.5,
                      "members": 12,
                      "admins": 2,
                      "offboarding": {
                        "status": "active",
                        "retention_years": null,
                        "started_at": null,
                        "window_ends_at": null,
                        "left_at": null,
                        "retention_ends_at": null,
                        "steps_done": 0
                      }
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createTenant",
        "summary": "Register a tenant",
        "description": "Audited (`tenant.create`). Allowed for platform_admin only. Tenants cannot be renamed or deleted through the API.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TenantCreate"
              },
              "example": {
                "id": "coop-dl",
                "name": "Dak Lak durian co-op"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new tenant.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Tenant"
                },
                "example": {
                  "id": "coop-dl",
                  "name": "Dak Lak durian co-op",
                  "source": "manual",
                  "created_at": 1790000000.5,
                  "members": 12,
                  "admins": 2,
                  "offboarding": {
                    "status": "active",
                    "retention_years": null,
                    "started_at": null,
                    "window_ends_at": null,
                    "left_at": null,
                    "retention_ends_at": null,
                    "steps_done": 0
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a malformed id or name, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_id": {
                    "value": {
                      "error": "invalid id: 2 to 64 lower-case letters, digits or hyphens, not starting with a hyphen",
                      "code": "invalid_id"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The id is taken. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant_already_exists": {
                    "value": {
                      "error": "tenant already exists",
                      "code": "tenant_already_exists"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/tenants/{id}/admins": {
      "get": {
        "operationId": "listTenantAdmins",
        "summary": "A company's admins",
        "description": "SELF-1-3 (#184). The company admins of a company that the platform's admin recovery can reset (never an account that is also a platform admin or a lab user): id, email, name and account status, never a password or a link. Allowed for platform_admin through a signed-in session only. An unknown company is a 404.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The company (tenant id).",
            "schema": {
              "type": "string"
            },
            "example": "coop-new"
          }
        ],
        "responses": {
          "200": {
            "description": "The company's admins, by email.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TenantAdminList"
                },
                "example": {
                  "items": [
                    {
                      "user_id": 4,
                      "email": "boss@coop-new.example",
                      "display_name": "Chi Lan",
                      "status": "active"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: coop-new",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/tenants/{id}/admin-invitations": {
      "post": {
        "operationId": "createAdminInvitation",
        "summary": "Invite a company's first admin (link shown once)",
        "description": "SELF-1-3 (#184). Creates a one-time link that lets the person with `email` choose a password and join the company as tenant_admin (or, when the email has an account, sign in and join). The link is returned once (`no-store`) and works once, for 72 hours, unless revoked; only the SHA-256 of its token is stored, so no read ever returns it. With an active company admin (an active membership and account) in place, a further invitation is the platform's admin recovery and needs a `reason`. Audited (`account_link.create`, in the same transaction, in the company's own log: purpose, role, reason, expiry; never the link). Allowed for platform_admin through a signed-in session only; the session must have confirmed its password within the last 10 minutes (SELF-1-2), else 401 `reauthentication_required` before anything is done.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The company (tenant id).",
            "schema": {
              "type": "string"
            },
            "example": "coop-new"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AdminInvitationCreate"
              },
              "example": {
                "email": "first.admin@coop-new.example",
                "display_name": "Chi Lan"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The link, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountLinkCreated"
                },
                "example": {
                  "id": 12,
                  "link": "https://txng.theio.vn/login#invite=agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790259200.5,
                  "emailed": true
                },
                "x-sdk-example": {
                  "id": 12,
                  "link": "https://txng.theio.vn/login#invite=agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790259200.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad email, display name or reason, a missing reason when the company already has an admin, or a bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the link, whose token is never stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "email": {
                    "value": {
                      "error": "invalid email",
                      "code": "invalid_email"
                    }
                  },
                  "reason_required": {
                    "value": {
                      "error": "reason is required: the company already has an admin",
                      "code": "reason_is_required"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: role",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: coop-new",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "A company cap is reached: at most 50 pending links, and 30 new links an hour. SELF-2-4 (#193): or the company has left CropPath (`company_left`): its people are off and their personal data removed, so no link is made for it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "pending": {
                    "value": {
                      "error": "too many pending links: at most 50 per company",
                      "code": "too_many_pending_links"
                    }
                  },
                  "hourly": {
                    "value": {
                      "error": "too many links: at most 30 per company per hour",
                      "code": "too_many_links"
                    }
                  },
                  "company_left": {
                    "value": {
                      "error": "company left: the company has left CropPath; nobody can join it or be let back in",
                      "code": "company_left"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/tenants/{id}/admins/{user_id}/recovery-link": {
      "post": {
        "operationId": "createAdminRecoveryLink",
        "summary": "Let a company admin set a new password (link shown once)",
        "description": "SELF-1-3 (#184). The platform's admin recovery: a one-time link that lets a company admin of the company choose a new password; accepting it ends every session of that account. Returned once (`no-store`); works once, for 24 hours, unless revoked; only the SHA-256 of its token is stored. A `reason` is required. Audited (`account_link.create`, in the same transaction, in the company's own log, so the company sees it: purpose, role, reason, expiry; never the link). Someone who is not an admin of this company, an account that is also a platform admin or a lab user (no link resets one; a link made before the account gained such a role stops working), or no such account, is a 404. Allowed for platform_admin through a signed-in session only, with a password confirmed within the last 10 minutes (SELF-1-2).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The company (tenant id).",
            "schema": {
              "type": "string"
            },
            "example": "coop-new"
          },
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The company admin's account id (from listTenantAdmins).",
            "schema": {
              "type": "string"
            },
            "example": "4"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RecoveryLinkCreate"
              },
              "example": {
                "reason": "Lost phone, cannot sign in"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The link, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountLinkCreated"
                },
                "example": {
                  "id": 12,
                  "link": "https://txng.theio.vn/login#reset=agr_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790086400.5,
                  "emailed": true
                },
                "x-sdk-example": {
                  "id": 12,
                  "link": "https://txng.theio.vn/login#reset=agr_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790086400.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing or bad reason, or a bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the link, whose token is never stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason_required": {
                    "value": {
                      "error": "reason is required",
                      "code": "reason_is_required"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: 1 to 200 characters on one line",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company, or no admin of it with that id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 4",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "A company cap is reached: at most 50 pending links, and 30 new links an hour. SELF-2-4 (#193): or the company has left CropPath (`company_left`): its people are off and their personal data removed, so no link is made for it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "pending": {
                    "value": {
                      "error": "too many pending links: at most 50 per company",
                      "code": "too_many_pending_links"
                    }
                  },
                  "hourly": {
                    "value": {
                      "error": "too many links: at most 30 per company per hour",
                      "code": "too_many_links"
                    }
                  },
                  "company_left": {
                    "value": {
                      "error": "company left: the company has left CropPath; nobody can join it or be let back in",
                      "code": "company_left"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members": {
      "get": {
        "operationId": "listMembers",
        "summary": "List the company's members",
        "description": "SELF-1-4 (#185). Everyone who belongs to the selected company, by email: their role here (and an operator's facilities), platform-managed roles shown read-only, whether the company turned them off, the account status, the last sign-in and when they joined; and how many active admins the company has. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The members.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MemberList"
                },
                "example": {
                  "items": [
                    {
                      "user_id": 7,
                      "email": "lan@coop-dl.example",
                      "display_name": "Chi Lan",
                      "role": "operator",
                      "facilities": [
                        "VN-TGPH-021"
                      ],
                      "other_roles": [],
                      "lab_id": null,
                      "status": "active",
                      "account_status": "active",
                      "last_sign_in_at": 1790086400.5,
                      "joined_at": 1789000000.0,
                      "two_factor": false,
                      "locked": false
                    }
                  ],
                  "active_admins": 1
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members/{user_id}": {
      "patch": {
        "operationId": "updateMember",
        "summary": "Change a member's role or facilities",
        "description": "SELF-1-4 (#185). One role per member in this company: saving replaces the member's memberships of the roles tenant_admin, operator and auditor here with one (lab and platform admin memberships are never changed; an account with only those is not a member here and answers 404: it joins the company through an invitation); the member's status here, when they joined and their notice acceptance are kept. An operator may be limited to facilities of the company. Takes effect on the member's next request. A change that takes the tenant_admin role away revokes every pending invitation and password link of this company that the member created. Changing a role to or from tenant_admin needs a password confirmed within the last 10 minutes (SELF-1-2). The last-admin rule: a change that would leave the company with no active company admin whose account is active is 409 `last_admin`. Audited (`member.update`, in the same transaction: the new role and facilities and the previous ones). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The member's account id (from listMembers).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MemberUpdate"
              },
              "example": {
                "role": "operator",
                "facilities": [
                  "VN-TGPH-021"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The member, changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Member"
                },
                "example": {
                  "user_id": 7,
                  "email": "lan@coop-dl.example",
                  "display_name": "Chi Lan",
                  "role": "operator",
                  "facilities": [
                    "VN-TGPH-021"
                  ],
                  "other_roles": [],
                  "lab_id": null,
                  "status": "active",
                  "account_status": "active",
                  "last_sign_in_at": 1790086400.5,
                  "joined_at": 1789000000.0,
                  "two_factor": false,
                  "locked": false
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing or unknown role, facilities for a role other than operator or a facility the company does not have, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "role": {
                    "value": {
                      "error": "invalid role: one of tenant_admin, operator, auditor",
                      "code": "invalid_role"
                    }
                  },
                  "facility": {
                    "value": {
                      "error": "unknown facility: VN-TGPH-999",
                      "code": "unknown_facility"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: email",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago while the change involves the company admin role (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such member of this company: no role tenant_admin, operator or auditor here (a lab-only account, or another company's member, answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The change would leave the company without an active admin.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "last admin: a company needs at least one active admin",
                  "code": "last_admin"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members/{user_id}/disable": {
      "post": {
        "operationId": "disableMember",
        "summary": "Turn a member off for this company",
        "description": "SELF-1-4 (#185). Turns the member's memberships of the roles tenant_admin, operator and auditor in this company off: from the next request on they cannot act for this company and it leaves their company picker; every other company they belong to is unchanged, and the account itself (managed by CropPath) too. When they have no active membership left anywhere, their sessions end. Every pending invitation and password link of this company that they created is revoked in the same change. Needs a password confirmed within the last 10 minutes (SELF-1-2). The last-admin rule applies (409 `last_admin`). Audited (`member.disable`, in the same transaction). Repeating it changes nothing (200). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The member's account id (from listMembers).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The member.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Member"
                },
                "example": {
                  "user_id": 7,
                  "email": "lan@coop-dl.example",
                  "display_name": "Chi Lan",
                  "role": "operator",
                  "facilities": [
                    "VN-TGPH-021"
                  ],
                  "other_roles": [],
                  "lab_id": null,
                  "status": "disabled",
                  "account_status": "active",
                  "last_sign_in_at": 1790086400.5,
                  "joined_at": 1789000000.0,
                  "two_factor": false,
                  "locked": false
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (always asked here) (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No member of this company with a role it manages (tenant_admin, operator or auditor).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The last-admin rule (turning off the company's only active admin). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "last_admin": {
                    "value": {
                      "error": "last admin: a company needs at least one active admin",
                      "code": "last_admin"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members/{user_id}/enable": {
      "post": {
        "operationId": "enableMember",
        "summary": "Turn a member back on for this company",
        "description": "SELF-1-4 (#185). Turns the member's memberships in this company back on, as they were (role and facilities). Turning a company admin back on gives the admin role again, so it needs a password confirmed within the last 10 minutes (SELF-1-2), as inviting an admin does. Audited (`member.enable`, in the same transaction). Repeating it changes nothing (200). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The member's account id (from listMembers).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The member.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Member"
                },
                "example": {
                  "user_id": 7,
                  "email": "lan@coop-dl.example",
                  "display_name": "Chi Lan",
                  "role": "operator",
                  "facilities": [
                    "VN-TGPH-021"
                  ],
                  "other_roles": [],
                  "lab_id": null,
                  "status": "active",
                  "account_status": "active",
                  "last_sign_in_at": 1790086400.5,
                  "joined_at": 1789000000.0,
                  "two_factor": false,
                  "locked": false
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token; or, for a company admin, a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No member of this company with a role it manages (tenant_admin, operator or auditor).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The company has its maximum of 200 active members and pending invitations. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "too_many_members": {
                    "value": {
                      "error": "too many members: at most 200 active members and pending invitations per company",
                      "code": "too_many_members"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members/{user_id}/password-link": {
      "post": {
        "operationId": "createMemberPasswordLink",
        "summary": "Create a new password link for a member (shown once)",
        "description": "SELF-1-4 (#185). A one-time link (24 hours) with which the member chooses a new password; accepting it ends every session of the account and opens a new one (POST /v1/auth/links/accept). Returned once (`no-store`); only the SHA-256 of its token is stored. It never shows or changes two-step sign-in. Refused with 409 `reset_by_support` unless every active membership of the account is in this company and the account is no platform admin or lab user (the answer names no other company). Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`account_link.create`, in the same transaction: purpose `reset`, role, expiry; never the link). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The member's account id (from listMembers).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          }
        ],
        "responses": {
          "201": {
            "description": "The link, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountLinkCreated"
                },
                "example": {
                  "id": 13,
                  "link": "https://txng.theio.vn/login#reset=agr_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790086400.5,
                  "emailed": true
                },
                "x-sdk-example": {
                  "id": 13,
                  "link": "https://txng.theio.vn/login#reset=agr_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790086400.5
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the link, whose token is never stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (always asked here) (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No active member of this company with a role it manages.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Only CropPath support may reset this account, or a company cap is reached (at most 50 pending links, and 30 new links an hour).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "reset_by_support": {
                    "value": {
                      "error": "reset by support: this account can only be reset by CropPath support",
                      "code": "reset_by_support"
                    }
                  },
                  "pending": {
                    "value": {
                      "error": "too many pending links: at most 50 per company",
                      "code": "too_many_pending_links"
                    }
                  },
                  "hourly": {
                    "value": {
                      "error": "too many links: at most 30 per company per hour",
                      "code": "too_many_links"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members/{user_id}/two-factor/reset": {
      "post": {
        "operationId": "resetMemberTwoFactor",
        "summary": "Remove a member's two-step sign-in (a lost phone)",
        "description": "SELF-1-6 (#187). Removes the member's authenticator app, backup codes and pending sign-ins and ends every session of theirs; they sign in with the password alone and set the app up again. A company admin may reset a member who belongs to this company only and holds no platform admin or lab role (409 `reset_by_support` otherwise: CropPath support resets those); a platform admin acting for the company (CropPath support) may reset any member of it and must give a `reason`, kept in the company's activity log. Repeating it changes nothing (200). Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`auth.two_factor.reset`, in the same transaction): one row in this company's activity log and, when the account belongs to other companies too (a platform admin's reset), one more row in each of their logs, which does not name this company. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The member's account id (from listMembers).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TwoFactorReset"
              },
              "example": {
                "reason": "Lost phone, confirmed by Zalo call with the company director"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Reset.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TwoFactorResetResult"
                },
                "example": {
                  "user_id": 7,
                  "two_factor": false,
                  "sessions_revoked": 1
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a platform admin without a reason or a reason that is not one line of 1 to 200 characters, or a bad Idempotency-Key; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason_required": {
                    "value": {
                      "error": "reason is required",
                      "code": "reason_is_required"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: 1 to 200 characters on one line",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No member of this company with that id (another company's member answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Only CropPath support may reset this account (it belongs to another company too, or holds a platform admin or lab role); or the Idempotency-Key is in use.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "reset_by_support": {
                    "value": {
                      "error": "reset by support: this account can only be reset by CropPath support",
                      "code": "reset_by_support"
                    }
                  },
                  "in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members/{user_id}/sessions/revoke": {
      "post": {
        "operationId": "revokeMemberSessions",
        "summary": "Sign a member out everywhere (a lost phone)",
        "description": "SELF-2-1 (#190). Ends every session of the member, on every device; they sign in again with their password (and the second step, when on). Sessions belong to the person, not to a company, so this signs them out of every company they work for: a company admin may do it only for a member who belongs to this company alone and holds no platform admin or lab role (409 `sign_out_by_support` otherwise, which never names the other company: CropPath support does it); a platform admin acting for the company (CropPath support) may do it for any member of it and must give a `reason`, kept in the company's activity log. Another company's person answers 404 like a missing one. Repeating it ends nothing more (200). Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`member.sessions.revoke`, in the same transaction, with how many were ended). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The member's account id (from listMembers).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MemberSessionsRevoke"
              },
              "example": {
                "reason": "Phone lost at the collection point, confirmed by the company director"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Signed out everywhere.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MemberSessionsRevoked"
                },
                "example": {
                  "user_id": 7,
                  "sessions_revoked": 2
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a platform admin without a reason or a reason that is not one line of 1 to 200 characters, or a bad Idempotency-Key; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason_required": {
                    "value": {
                      "error": "reason is required",
                      "code": "reason_is_required"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: 1 to 200 characters on one line",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No member of this company with that id (another company's member answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Only CropPath support may sign this account out (it belongs to another company too, or holds a platform admin or lab role); or the Idempotency-Key is in use.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "sign_out_by_support": {
                    "value": {
                      "error": "sign out by support: only CropPath support can end this account's sessions",
                      "code": "sign_out_by_support"
                    }
                  },
                  "in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/members/{user_id}/unlock": {
      "post": {
        "operationId": "unlockMember",
        "summary": "Clear a member's sign-in lockout",
        "description": "SELF-2-10 (#199). Clears the login lockout of the member's email: wrong passwords and wrong two-step codes count together (10 in a row lock sign-in for 15 minutes), so one unlock clears both, and the count starts afresh. Nothing else changes: no session is opened or ended, a used-up sign-in step is not brought back (the person signs in with the password again), and a member turned off for this company stays turned off. The lockout belongs to the email, so it is shared by every company of the account: a company admin may unlock a member who belongs to this company only and holds no platform admin or lab role (409 `unlock_by_support` otherwise: CropPath support unlocks those); a platform admin acting for the company (CropPath support) may unlock any member of it. Repeating it changes nothing (200, `was_locked` false). Needs a password confirmed within the last 10 minutes (SELF-1-2). Audited (`member.unlock`, in the same transaction, one row in this company's activity log; never the email or a failure count). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "description": "The member's account id (from listMembers).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Unlocked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MemberUnlockResult"
                },
                "example": {
                  "user_id": 7,
                  "locked": false,
                  "was_locked": true
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No member of this company with that id (another company's member answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Only CropPath support may unlock this account (it belongs to another company too, or holds a platform admin or lab role); or the Idempotency-Key is in use.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unlock_by_support": {
                    "value": {
                      "error": "unlock by support: only CropPath support can unlock this account",
                      "code": "unlock_by_support"
                    }
                  },
                  "in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/invitations": {
      "get": {
        "operationId": "listInvitations",
        "summary": "List the company's invitations and password links",
        "description": "SELF-1-4 (#185). The company's invitation links and password links (`purpose`), newest first, one page: pending, used, expired and revoked, with who created them and when; never a link or its token. The platform's admin recovery links are not listed. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only the links in this state.",
            "schema": {
              "enum": [
                "pending",
                "used",
                "expired",
                "revoked"
              ]
            },
            "example": "pending"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 100).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 100
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "The invitations and password links.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvitationList"
                },
                "example": {
                  "items": [
                    {
                      "id": 12,
                      "purpose": "invite",
                      "email": "new.colleague@coop-dl.example",
                      "role": "operator",
                      "facilities": null,
                      "display_name": "Anh Minh",
                      "status": "pending",
                      "created_by": "boss@coop-dl.example",
                      "created_at": 1790000000.0,
                      "expires_at": 1790259200.0,
                      "used_at": null,
                      "used_by": null,
                      "revoked_at": null,
                      "revoked_by": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `status`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "value": {
                      "error": "invalid status: one of pending, used, expired, revoked",
                      "code": "invalid_status"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createInvitation",
        "summary": "Invite a colleague (link shown once)",
        "description": "SELF-1-4 (#185). A one-time link (72 hours) with which the person chooses a password and joins the company in `role` (or, when the email has a CropPath account, signs in with it and joins: the answer is the same either way). Returned once (`no-store`); only the SHA-256 of its token is stored. An email that is already an active member of this company is 409 `already_a_member`. Inviting a company admin needs a password confirmed within the last 10 minutes (SELF-1-2). The company holds at most 200 active members and pending invitations, 50 pending links and 30 new links an hour. Audited (`account_link.create`, in the same transaction: purpose `invite`, role, expiry; never the link). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/InvitationCreate"
              },
              "example": {
                "email": "new.colleague@coop-dl.example",
                "role": "operator",
                "facilities": null,
                "display_name": "Anh Minh"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The link, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountLinkCreated"
                },
                "example": {
                  "id": 12,
                  "link": "https://txng.theio.vn/login#invite=agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790259200.5,
                  "emailed": true
                },
                "x-sdk-example": {
                  "id": 12,
                  "link": "https://txng.theio.vn/login#invite=agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790259200.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad email, role, display name or facility, facilities for a role other than operator, or a bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the link, whose token is never stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "email": {
                    "value": {
                      "error": "invalid email",
                      "code": "invalid_email"
                    }
                  },
                  "role": {
                    "value": {
                      "error": "invalid role: one of tenant_admin, operator, auditor",
                      "code": "invalid_role"
                    }
                  },
                  "facility": {
                    "value": {
                      "error": "unknown facility: VN-TGPH-999",
                      "code": "unknown_facility"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: reason",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago while inviting a company admin (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company (a platform admin's X-Tenant names none).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: coop-new",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The email is already an active member, or a company cap is reached.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "already_a_member": {
                    "value": {
                      "error": "already a member: this email is already an active member of the company",
                      "code": "already_a_member"
                    }
                  },
                  "too_many_members": {
                    "value": {
                      "error": "too many members: at most 200 active members and pending invitations per company",
                      "code": "too_many_members"
                    }
                  },
                  "pending": {
                    "value": {
                      "error": "too many pending links: at most 50 per company",
                      "code": "too_many_pending_links"
                    }
                  },
                  "hourly": {
                    "value": {
                      "error": "too many links: at most 30 per company per hour",
                      "code": "too_many_links"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/invitations/{id}/revoke": {
      "post": {
        "operationId": "revokeInvitation",
        "summary": "Revoke a pending invitation or password link",
        "description": "SELF-1-4 (#185). The invitation or password link stops working at once. Audited (`account_link.revoke`, in the same transaction, with the link's purpose). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403), so no integration manages people.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The link id (from listInvitations).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The link, revoked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvitationRevoked"
                },
                "example": {
                  "id": 12,
                  "status": "revoked"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No pending invitation or password link of this company with this id (used, revoked, the platform's admin recovery link, or another company's).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/volumes/{growing_area}/{season}": {
      "get": {
        "operationId": "getVolume",
        "summary": "Declared volume of a growing area and season",
        "description": "Cross-tenant aggregate for one growing area: only totals, never other tenants' records. An unknown growing area or season answers 200, never 404: `declared_kg` is 0 when nothing is declared for that area and season, and `cap_kg` is null only for an unknown growing area or for an area a company added that CropPath has not approved yet (otherwise it is the area's `area_ha` times `yield_kg_per_ha`, whatever the season).",
        "tags": [
          "integrity"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "aggregate_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "growing_area",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-DL-SR-0123"
          },
          {
            "name": "season",
            "in": "path",
            "required": true,
            "description": "Season label (the calendar year by default).",
            "schema": {
              "type": "string"
            },
            "example": "2026"
          }
        ],
        "responses": {
          "200": {
            "description": "Totals.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Volume"
                },
                "example": {
                  "growing_area": "VN-DL-SR-0123",
                  "season": "2026",
                  "declared_kg": 1200.5,
                  "cap_kg": 20000.0
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (interim tenant_admin or platform_admin guard until per-route policies land) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/cartons": {
      "get": {
        "operationId": "listLotCartons",
        "summary": "A lot's cartons",
        "description": "The cartons of the lot by number, with their contents' count and measured weight. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJjYXJ0b25fbm8iOjUwfQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of cartons.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CartonPage"
                },
                "example": {
                  "items": [
                    {
                      "tenant": "coop-dl",
                      "code": "C-014-0017",
                      "lot": "LO-260928-014",
                      "carton_no": 17,
                      "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                      "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                      "net_mass_kg": 8.53,
                      "fruit_count": 3,
                      "fruit_mass_kg": 8.89,
                      "labels_printed_at": 1790000300.5,
                      "created_by": "packer@coop.example",
                      "created_at": 1790000300.5,
                      "updated_at": 1790000310.0
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad cursor or limit, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createCarton",
        "summary": "Add a carton to a lot",
        "description": "A new empty carton of the lot: the next number, its code, public id and GS1 serial; creation is its label's print time. The lot must be open or closed. Audited (`carton.create`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CartonCreate"
              },
              "example": {}
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new carton.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CartonDetail"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "C-014-0017",
                  "lot": "LO-260928-014",
                  "carton_no": 17,
                  "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                  "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                  "net_mass_kg": null,
                  "fruit_count": 0,
                  "fruit_mass_kg": 0.0,
                  "labels_printed_at": 1790000300.5,
                  "created_by": "packer@coop.example",
                  "created_at": 1790000300.5,
                  "updated_at": 1790000300.5,
                  "fruits": []
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a field in the body, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot is not open or closed, or already has 9999 cartons. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_is_draft": {
                    "value": {
                      "error": "lot is draft",
                      "code": "lot_is_draft"
                    }
                  },
                  "lot_is_packed": {
                    "value": {
                      "error": "lot is packed",
                      "code": "lot_is_packed"
                    }
                  },
                  "too_many_cartons": {
                    "value": {
                      "error": "too many cartons: a lot holds at most 9999",
                      "code": "too_many_cartons"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/cartons/{code}": {
      "get": {
        "operationId": "getCarton",
        "summary": "A carton and its fruits",
        "description": "The carton with the codes of its fruits. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Carton code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "C-014-0017"
          }
        ],
        "responses": {
          "200": {
            "description": "The carton.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CartonDetail"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "C-014-0017",
                  "lot": "LO-260928-014",
                  "carton_no": 17,
                  "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                  "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                  "net_mass_kg": 8.53,
                  "fruit_count": 3,
                  "fruit_mass_kg": 8.89,
                  "labels_printed_at": 1790000300.5,
                  "created_by": "packer@coop.example",
                  "created_at": 1790000300.5,
                  "updated_at": 1790000310.0,
                  "fruits": [
                    "Q-014-0049",
                    "Q-014-0050",
                    "Q-014-0052"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such carton for this tenant: a carton of another tenant, or of a lot outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: C-014-0017",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/cartons/{code}/fruits": {
      "put": {
        "operationId": "setCartonContents",
        "summary": "Set what a carton holds",
        "description": "Replaces the carton's fruits and its weighed net mass. Every fruit must be a fruit of the carton's lot that is packable (status recorded or overridden, grade A or B: a rejected fruit cannot be packed) and in no other carton; the lot must be open or closed. Audited (`carton.contents.set`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Carton code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "C-014-0017"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CartonContents"
              },
              "example": {
                "fruits": [
                  "Q-014-0049",
                  "Q-014-0050",
                  "Q-014-0052"
                ],
                "net_mass_kg": 8.53
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The carton with its new contents.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CartonDetail"
                },
                "example": {
                  "tenant": "coop-dl",
                  "code": "C-014-0017",
                  "lot": "LO-260928-014",
                  "carton_no": 17,
                  "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                  "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                  "net_mass_kg": 8.53,
                  "fruit_count": 3,
                  "fruit_mass_kg": 8.89,
                  "labels_printed_at": 1790000300.5,
                  "created_by": "packer@coop.example",
                  "created_at": 1790000300.5,
                  "updated_at": 1790000310.0,
                  "fruits": [
                    "Q-014-0049",
                    "Q-014-0050",
                    "Q-014-0052"
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not exactly fruits and net_mass_kg, bad fruit codes or mass, a code that is not a fruit of the carton's lot, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: exactly fruits and net_mass_kg",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_fruits": {
                    "value": {
                      "error": "invalid fruits: 1 to 32 distinct fruit codes",
                      "code": "invalid_fruits"
                    }
                  },
                  "invalid_net_mass_kg": {
                    "value": {
                      "error": "invalid net_mass_kg: a number above 0 and at most 1000",
                      "code": "invalid_net_mass_kg"
                    }
                  },
                  "unknown_fruit": {
                    "value": {
                      "error": "unknown fruit: Q-014-0300 is not a fruit of lot LO-260928-014",
                      "code": "unknown_fruit"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such carton for this tenant: a carton of another tenant, or of a lot outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: C-014-0017",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot is not open or closed, a fruit is not packable, or a fruit is in another carton.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_is_packed": {
                    "value": {
                      "error": "lot is packed",
                      "code": "lot_is_packed"
                    }
                  },
                  "fruit_not_packable": {
                    "value": {
                      "error": "fruit not packable: Q-014-0007 is rejected",
                      "code": "fruit_not_packable"
                    }
                  },
                  "fruit_already_packed": {
                    "value": {
                      "error": "fruit already packed: Q-014-0049 is in carton C-014-0016",
                      "code": "fruit_already_packed"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/seal": {
      "post": {
        "operationId": "sealLot",
        "summary": "Record a seal number (the first one packs the lot)",
        "description": "Records a seal number on the lot. The first one is the pack event: the lot must be open or closed and have at least one carton, every carton holding fruit and a net mass with every fruit still packable. An open lot is first closed in the same transaction, as a lot close does (its open or paused measurement sessions are closed and its closed_at set to the pack time; domain model `closed(sealed) -> packed`); the lot then becomes `packed` with its packed totals, and its cartons never change again. A later seal number of a packed lot is a seal change (appended). The seal itself is tenant-entered. The packing step is Device-recorded only when a packing station of the lot's facility (profile vn.agritrace.pack-station) signed pack events through ingest before this call that cover every carton with its current fruits and net mass and this seal number, from a key never revoked for compromise; the pack freezes the lot's packing evidence, so a later pack event cannot raise the sealed tier (#136). A pack event of the lot, accepted or held, whose claims name another seal number than this pack seal raises a `pack_mismatch` alert, and an accepted one goes back to quarantine, so the lot is on hold until a reviewer decides; the seal is still recorded. Otherwise the packing step is Self-declared. #273 (owner decision D5): the pack event is refused (409 `address_not_coded`, with `details` naming each record) while the lot's packing house, its growing area or the company profile in Viet Nam has no address picked from the official list of administrative units (a province and a commune; Viet Nam has had no district level since 2025-07-01); a later seal change of a packed lot is not checked. Audited (`lot.seal`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SealRequest"
              },
              "example": {
                "seal_no": "0492117"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The lot's packing after the seal.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotPacking"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "status": "packed",
                  "packed_at": 1790003600.0,
                  "cartons": 41,
                  "fruits": 123,
                  "net_mass_kg": 349.6,
                  "fruit_mass_kg": 364.2,
                  "seal_numbers": [
                    {
                      "seal_no": "0492117",
                      "sealed_by": "packer@coop.example",
                      "sealed_at": 1790003600.0
                    }
                  ],
                  "mass_balance": {
                    "tolerance": 0.05,
                    "violation_count": 0,
                    "violations": [],
                    "lot": {
                      "exportable_fruits": 123,
                      "exportable_kg": 364.2,
                      "uncartoned_fruits": 0,
                      "uncartoned_kg": 0.0,
                      "violation": null
                    },
                    "area": {
                      "growing_area": "VN-TGOR-0387",
                      "season": "2026",
                      "harvested_kg": 1820.0,
                      "declared_kg": 1820.0,
                      "shipped_kg": 1230.0,
                      "packed_lots": 4,
                      "violation": null
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not exactly seal_no, a bad seal number, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: exactly seal_no",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_seal_no": {
                    "value": {
                      "error": "invalid seal_no: 1 to 64 letters, digits, '.', '_' or '-', starting with a letter or digit",
                      "code": "invalid_seal_no"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot cannot be sealed or packed yet (including `address_not_coded`: an address the pack event would seal is not coded yet, each record in `details`), or already has this seal number. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_is_draft": {
                    "value": {
                      "error": "lot is draft",
                      "code": "lot_is_draft"
                    }
                  },
                  "no_cartons": {
                    "value": {
                      "error": "no cartons: a lot is packed into at least one carton",
                      "code": "no_cartons"
                    }
                  },
                  "carton_not_ready": {
                    "value": {
                      "error": "carton not ready: C-014-0003 (carton_empty, carton_unweighed)",
                      "code": "carton_not_ready"
                    }
                  },
                  "address_not_coded": {
                    "value": {
                      "error": "address not coded: pick the official province and commune of the lot's packing house VN-TGPH-021, growing area VN-TGOR-0387, company profile before packing it (Viet Nam has no district level since 2025-07-01)",
                      "code": "address_not_coded",
                      "details": [
                        {
                          "kind": "facility",
                          "code": "VN-TGPH-021"
                        },
                        {
                          "kind": "growing_area",
                          "code": "VN-TGOR-0387"
                        },
                        {
                          "kind": "company_profile",
                          "code": null
                        }
                      ]
                    }
                  },
                  "seal_number_already_recorded": {
                    "value": {
                      "error": "seal number already recorded",
                      "code": "seal_number_already_recorded"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "The lot cannot be sealed or packed yet, or already has this seal number. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                },
                "Retry-After": {
                  "$ref": "#/components/headers/Retry-After"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "lot_is_draft": {
                      "value": {
                        "error": "lot is draft",
                        "code": "lot_is_draft"
                      }
                    },
                    "no_cartons": {
                      "value": {
                        "error": "no cartons: a lot is packed into at least one carton",
                        "code": "no_cartons"
                      }
                    },
                    "carton_not_ready": {
                      "value": {
                        "error": "carton not ready: C-014-0003 (carton_empty, carton_unweighed)",
                        "code": "carton_not_ready"
                      }
                    },
                    "seal_number_already_recorded": {
                      "value": {
                        "error": "seal number already recorded",
                        "code": "seal_number_already_recorded"
                      }
                    },
                    "idempotency_key_in_use": {
                      "value": {
                        "error": "idempotency key in use: retry later",
                        "code": "idempotency_key_in_use"
                      }
                    },
                    "idempotency_key_used": {
                      "value": {
                        "error": "idempotency key used: the response is too large to replay",
                        "code": "idempotency_key_used"
                      }
                    },
                    "idempotency_key_unrecorded": {
                      "value": {
                        "error": "idempotency key used: the request ran but its response was not recorded",
                        "code": "idempotency_key_used"
                      }
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Records a seal number on the lot. The first one is the pack event: the lot must be open or closed and have at least one carton, every carton holding fruit and a net mass with every fruit still packable. An open lot is first closed in the same transaction, as a lot close does (its open or paused measurement sessions are closed and its closed_at set to the pack time; domain model `closed(sealed) -> packed`); the lot then becomes `packed` with its packed totals, and its cartons never change again. A later seal number of a packed lot is a seal change (appended). The seal itself is tenant-entered. The packing step is Device-recorded only when a packing station of the lot's facility (profile vn.agritrace.pack-station) signed pack events through ingest before this call that cover every carton with its current fruits and net mass and this seal number, from a key never revoked for compromise; the pack freezes the lot's packing evidence, so a later pack event cannot raise the sealed tier (#136). A pack event of the lot, accepted or held, whose claims name another seal number than this pack seal raises a `pack_mismatch` alert, and an accepted one goes back to quarantine, so the lot is on hold until a reviewer decides; the seal is still recorded. Otherwise the packing step is Self-declared. Audited (`lot.seal`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused."
      }
    },
    "/v1/lots/{lot}/packing": {
      "get": {
        "operationId": "getLotPacking",
        "summary": "A lot's packing and mass balance",
        "description": "Packed totals, seal numbers and the mass balance: per carton (empty, unweighed, a fruit no longer packable, a fruit without a scale weight, a net mass more than 5 % off its fruits' measured weights) and for the lot's growing area and season (harvested against shipped kg, across all tenants). Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's packing.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotPacking"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "status": "packed",
                  "packed_at": 1790003600.0,
                  "cartons": 41,
                  "fruits": 123,
                  "net_mass_kg": 349.6,
                  "fruit_mass_kg": 364.2,
                  "seal_numbers": [
                    {
                      "seal_no": "0492117",
                      "sealed_by": "packer@coop.example",
                      "sealed_at": 1790003600.0
                    }
                  ],
                  "mass_balance": {
                    "tolerance": 0.05,
                    "violation_count": 0,
                    "violations": [],
                    "lot": {
                      "exportable_fruits": 123,
                      "exportable_kg": 364.2,
                      "uncartoned_fruits": 0,
                      "uncartoned_kg": 0.0,
                      "violation": null
                    },
                    "area": {
                      "growing_area": "VN-TGOR-0387",
                      "season": "2026",
                      "harvested_kg": 1820.0,
                      "declared_kg": 1820.0,
                      "shipped_kg": 1230.0,
                      "packed_lots": 4,
                      "violation": null
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/pallets": {
      "get": {
        "operationId": "listPallets",
        "summary": "The company's pallets",
        "description": "#161: newest first, one page (`limit`, default 50, at most 200; `cursor`), optionally of one facility. Same roles as reading lots; an operator reads its facilities' pallets. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "packing"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "facility",
            "in": "query",
            "required": false,
            "description": "Only this facility's pallets.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of pallets.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PalletPage"
                },
                "example": {
                  "items": [
                    {
                      "sscc": "095200000000000011",
                      "facility": "VN-TGPH-021",
                      "epc": "https://id.gs1.org/00/095200000000000011",
                      "element_string": "(00)095200000000000011",
                      "carton_count": 40,
                      "created_by": "packer@coop.example",
                      "created_at": 1790000000.5,
                      "updated_at": 1790000060.5
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit`, `cursor` or `facility`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createPallet",
        "summary": "Create a pallet",
        "description": "#161: an empty pallet of one of the company's approved facilities, identified by an SSCC: allocated from the platform's GS1 company prefix (409 while none is configured), or one of the company's own GS1 membership. The SSCC is unique within the company (pallets and container loads). Same roles as writing lots; an operator within its facilities. Audited (`pallet.create`) in the company's activity log. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "packing"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PalletCreate"
              },
              "example": {
                "facility": "VN-TGPH-021"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The pallet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pallet"
                },
                "example": {
                  "sscc": "095200000000000011",
                  "facility": "VN-TGPH-021",
                  "epc": "https://id.gs1.org/00/095200000000000011",
                  "element_string": "(00)095200000000000011",
                  "cartons": [],
                  "created_by": "packer@coop.example",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "An unknown or malformed field (an unknown facility, an SSCC whose check digit is wrong or that carries the platform's prefix), invalid JSON, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_facility": {
                    "value": {
                      "error": "unknown facility",
                      "code": "unknown_facility"
                    }
                  },
                  "invalid_sscc": {
                    "value": {
                      "error": "invalid sscc: 18 digits with a valid GS1 check digit",
                      "code": "invalid_sscc"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The facility is a proposal not yet approved, the SSCC is in use by the company, no GS1 company prefix is configured; or the Idempotency-Key's first request is still running.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "facility_not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  },
                  "sscc": {
                    "value": {
                      "error": "sscc already in use by the company",
                      "code": "sscc_already_in_use_by_the_company"
                    }
                  },
                  "prefix": {
                    "value": {
                      "error": "prefix not configured: the platform has no GS1 company prefix yet; enter a number of the company's own GS1 membership",
                      "code": "prefix_not_configured"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/pallets/{sscc}": {
      "get": {
        "operationId": "getPallet",
        "summary": "One pallet with its cartons",
        "description": "#161: the pallet, its GS1-128 element string and EPC, and the cartons on it. Same roles as reading lots. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "packing"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "sscc",
            "in": "path",
            "required": true,
            "description": "The pallet's SSCC (18 digits).",
            "schema": {
              "type": "string"
            },
            "example": "095200000000000011"
          }
        ],
        "responses": {
          "200": {
            "description": "The pallet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pallet"
                },
                "example": {
                  "sscc": "095200000000000011",
                  "facility": "VN-TGPH-021",
                  "epc": "https://id.gs1.org/00/095200000000000011",
                  "element_string": "(00)095200000000000011",
                  "cartons": [
                    {
                      "code": "C-014-0001",
                      "lot": "LO-260928-014",
                      "epc": "https://id.gs1.org/01/09520000000011/21/Xk3pQ9vT2mLr7Wb4Yz1A"
                    }
                  ],
                  "created_by": "packer@coop.example",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000060.5
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such pallet for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 095200000000000011",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/pallets/{sscc}/cartons": {
      "put": {
        "operationId": "setPalletCartons",
        "summary": "Set the cartons on a pallet",
        "description": "#161: replaces what the pallet holds (0 to 200 cartons): cartons of packed lots of the pallet's facility, each on one pallet at most. The lot's EPCIS document then carries the aggregation of its cartons into the pallet. A pallet whose cartons left on a departed shipment never changes. #267: a writer names the cartons it read on the pallet (`expected_cartons`); the server checks them inside the write, after locking the pallet, and answers 409 `pallet_changed` when the pallet holds other cartons, so a stale write never overwrites a change made since. Same roles as writing lots. Audited (`pallet.cartons.set`) in the company's activity log; a refused set writes only its failed row (`pallet.cartons.set.failed`). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "packing"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "sscc",
            "in": "path",
            "required": true,
            "description": "The pallet's SSCC (18 digits).",
            "schema": {
              "type": "string"
            },
            "example": "095200000000000011"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PalletCartons"
              },
              "example": {
                "cartons": [
                  "C-014-0001",
                  "C-014-0002"
                ],
                "expected_cartons": [
                  "C-014-0001"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The pallet with its cartons.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pallet"
                },
                "example": {
                  "sscc": "095200000000000011",
                  "facility": "VN-TGPH-021",
                  "epc": "https://id.gs1.org/00/095200000000000011",
                  "element_string": "(00)095200000000000011",
                  "cartons": [
                    {
                      "code": "C-014-0001",
                      "lot": "LO-260928-014",
                      "epc": "https://id.gs1.org/01/09520000000011/21/Xk3pQ9vT2mLr7Wb4Yz1A"
                    }
                  ],
                  "created_by": "packer@coop.example",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000060.5
                }
              }
            }
          },
          "400": {
            "description": "A body other than {\"cartons\": [...], \"expected_cartons\"?: [...]}, a code that is not a carton of the company at the pallet's facility, invalid JSON or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_cartons": {
                    "value": {
                      "error": "invalid cartons: at most 200 distinct carton codes",
                      "code": "invalid_cartons"
                    }
                  },
                  "invalid_expected_cartons": {
                    "value": {
                      "error": "invalid expected_cartons: at most 200 distinct carton codes",
                      "code": "invalid_expected_cartons"
                    }
                  },
                  "unknown_carton": {
                    "value": {
                      "error": "unknown carton: C-014-0003",
                      "code": "unknown_carton"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such pallet for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 095200000000000011",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The pallet holds other cartons than `expected_cartons` (it changed since the writer read it), a carton's lot is not packed, a carton is on another pallet, or the pallet or a carton left on a departed shipment.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "pallet_changed": {
                    "value": {
                      "error": "pallet changed: it holds other cartons than the ones read; read it again",
                      "code": "pallet_changed"
                    }
                  },
                  "lot_not_packed": {
                    "value": {
                      "error": "lot not packed: carton C-014-0003",
                      "code": "lot_not_packed"
                    }
                  },
                  "on_another_pallet": {
                    "value": {
                      "error": "carton on another pallet: C-014-0003",
                      "code": "carton_on_another_pallet"
                    }
                  },
                  "pallet_departed": {
                    "value": {
                      "error": "pallet departed: its cartons left on a departed shipment",
                      "code": "pallet_departed"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/mass-balance": {
      "get": {
        "operationId": "getGrowingAreaMassBalance",
        "summary": "Harvested against shipped kg of a growing area",
        "description": "The area's harvested kg of the season (its accepted harvest and receive envelopes, as its volume, plus its self-declared harvest declarations) against the packed net mass of its packed lots of the season, both across all tenants (aggregates only), with the violation stated. The area must be readable by the caller (own or unowned). Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused. Not audited (a read).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "season",
            "in": "query",
            "required": true,
            "description": "Season label (the calendar year by default).",
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9._-]{1,32}$"
            },
            "example": "2026"
          }
        ],
        "responses": {
          "200": {
            "description": "The area's mass balance.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AreaMassBalance"
                },
                "example": {
                  "growing_area": "VN-TGOR-0387",
                  "season": "2026",
                  "harvested_kg": 1820.0,
                  "declared_kg": 1820.0,
                  "shipped_kg": 1230.0,
                  "packed_lots": 4,
                  "violation": null
                }
              }
            }
          },
          "400": {
            "description": "A missing or malformed season, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "season_is_required": {
                    "value": {
                      "error": "season is required",
                      "code": "season_is_required"
                    }
                  },
                  "invalid_season": {
                    "value": {
                      "error": "invalid season: 1 to 32 letters, digits, dots, hyphens or underscores",
                      "code": "invalid_season"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growing-areas/{code}/harvests": {
      "get": {
        "operationId": "listHarvestDeclarations",
        "summary": "Harvest declarations of a growing area",
        "description": "The caller's tenant's own harvest declarations of the area (another tenant's are never listed; the mass balance counts them only as a sum), newest first with keyset pagination. A declaration is tenant-entered, so its source is self_declared. Allowed for platform_admin, tenant_admin, auditor and operator (operators read tenant-wide: a growing area carries no facility); lab is refused. Not audited (a read).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of harvest declarations.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6MTJ9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of harvest declarations.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestDeclarationPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 7,
                      "growing_area": "VN-TGOR-0387",
                      "harvest_date": "2026-09-27",
                      "season": "2026",
                      "kg": 1820.0,
                      "source": "self_declared",
                      "declared_by": "admin@coop-dl",
                      "declared_at": 1790500000.0
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit outside 1 to 200, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "declareHarvest",
        "summary": "Declare a harvest of a growing area",
        "description": "Records that the area harvested `kg` on `harvest_date`: tenant-entered, so its source is self_declared (no signed harvest event backs it). Only on an area of the caller's tenant (a platform_admin also on an unowned area); one declaration per area and date, never merged or overwritten; the date may not be later than today. Its season is the ingest policy's season of the harvest date (as a lot's), and the area's mass balance counts it in harvested_kg (and declared_kg). Audited (`growing_area.harvest.declare`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/HarvestDeclarationCreate"
              },
              "example": {
                "harvest_date": "2026-09-27",
                "kg": 1820
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The declaration.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestDeclaration"
                },
                "example": {
                  "id": 7,
                  "growing_area": "VN-TGOR-0387",
                  "harvest_date": "2026-09-27",
                  "season": "2026",
                  "kg": 1820.0,
                  "source": "self_declared",
                  "declared_by": "admin@coop-dl",
                  "declared_at": 1790500000.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not exactly harvest_date and kg, a bad date (or one later than today), a kg that is not a number above 0 and at most 1,000,000, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: exactly harvest_date and kg",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_harvest_date": {
                    "value": {
                      "error": "invalid harvest_date: later than today",
                      "code": "invalid_harvest_date"
                    }
                  },
                  "invalid_kg": {
                    "value": {
                      "error": "invalid kg: a number above 0 and at most 1000000",
                      "code": "invalid_kg"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this tenant: another tenant's area answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The area already has a harvest declaration for this date. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "harvest_already_declared": {
                    "value": {
                      "error": "harvest already declared: the area has a declaration for this date",
                      "code": "harvest_already_declared"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments": {
      "post": {
        "operationId": "createShipment",
        "summary": "Create a shipment",
        "description": "A new open shipment departing one of the tenant's facilities: container (ISO 6346), border gate, destination market, reefer setpoint and tolerance, and the independent temperature logger, a registered device of the departure facility (its keys stay in the device registry). Audited (`shipment.create`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities); auditor and lab are refused.",
        "tags": [
          "shipping"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ShipmentCreate"
              },
              "example": {
                "code": "SH-260930-01",
                "facility": "VN-TGPH-021",
                "container": "MSKU1234565",
                "border_gate": "Hữu Nghị",
                "destination": "CN",
                "setpoint_c": 13,
                "logger": {
                  "device_id": "reefer-logger-0731"
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new shipment.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Shipment"
                },
                "example": {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "setpoint_c": 13.0,
                  "tolerance_c": 2.0,
                  "logger_interval_minutes": 15,
                  "logger": {
                    "device_id": "reefer-logger-0731"
                  },
                  "status": "open",
                  "created_by": "shipper@coop.example",
                  "created_at": 1790040000.0,
                  "departed_by": null,
                  "departed_at": null,
                  "lots": [],
                  "logger_check": {
                    "status": "missing",
                    "readings": 0,
                    "considered": 0,
                    "first_at": null,
                    "last_at": null,
                    "min_c": null,
                    "max_c": null,
                    "seal_at": null,
                    "until": null,
                    "gap_count": 0,
                    "gaps": [],
                    "out_of_range_count": 0,
                    "out_of_range": [],
                    "complete": false,
                    "within_setpoint": false
                  },
                  "national_portal": {
                    "rows": 0,
                    "delivered": 0,
                    "pending": 0,
                    "failing": 0,
                    "filed": false
                  },
                  "consignee": null,
                  "documents": [],
                  "paperwork": {
                    "required": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "missing": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "complete": false
                  },
                  "amendments": []
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown or missing field, a bad value, a facility outside the tenant and scope, or a logger that is not a temperature logger of the registry at that facility; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_container": {
                    "value": {
                      "error": "invalid container: an ISO 6346 container number with a valid check digit",
                      "code": "invalid_container"
                    }
                  },
                  "invalid_destination": {
                    "value": {
                      "error": "invalid destination: one of CN",
                      "code": "invalid_destination"
                    }
                  },
                  "unknown_facility": {
                    "value": {
                      "error": "unknown facility",
                      "code": "unknown_facility"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The tenant already has a shipment with this code, or the logger is inactive. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded). SELF-2-8 (#197): or the facility is a company's proposal CropPath has not approved yet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "shipment_code_already_exists": {
                    "value": {
                      "error": "shipment code already exists",
                      "code": "shipment_code_already_exists"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  },
                  "facility_not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments/{code}": {
      "get": {
        "operationId": "getShipment",
        "summary": "A shipment, its lots, logger check and filing state",
        "description": "The shipment with its linked lots (seal recorded at the link against the current one), the logger cross-check and the national-portal filing state from the outbound backlog. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities). Not audited (a read).",
        "tags": [
          "shipping"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "SH-260930-01"
          }
        ],
        "responses": {
          "200": {
            "description": "The shipment.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Shipment"
                },
                "example": {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "setpoint_c": 13.0,
                  "tolerance_c": 2.0,
                  "logger_interval_minutes": 15,
                  "logger": {
                    "device_id": "reefer-logger-0731"
                  },
                  "status": "departed",
                  "created_by": "shipper@coop.example",
                  "created_at": 1790040000.0,
                  "departed_by": "shipper@coop.example",
                  "departed_at": 1790042400.0,
                  "lots": [
                    {
                      "lot": "LO-260928-014",
                      "status": "shipped",
                      "cartons": 41,
                      "seal_no": "0492117",
                      "sealed_at": 1790040600.0,
                      "current_seal_no": "0492117",
                      "seal_matches": true,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041000.0
                    }
                  ],
                  "logger_check": {
                    "status": "matched",
                    "readings": 9,
                    "considered": 9,
                    "first_at": 1790040600.0,
                    "last_at": 1790047800.0,
                    "min_c": 12.6,
                    "max_c": 13.4,
                    "seal_at": 1790040600.0,
                    "until": 1790042400.0,
                    "gap_count": 0,
                    "gaps": [],
                    "out_of_range_count": 0,
                    "out_of_range": [],
                    "complete": true,
                    "within_setpoint": true
                  },
                  "national_portal": {
                    "rows": 386,
                    "delivered": 386,
                    "pending": 0,
                    "failing": 0,
                    "filed": true
                  },
                  "consignee": null,
                  "documents": [],
                  "paperwork": {
                    "required": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "missing": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "complete": false
                  },
                  "amendments": []
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment for this tenant: a shipment of another tenant, or departing a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: SH-260930-01",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments/{code}/lots": {
      "post": {
        "operationId": "addShipmentLot",
        "summary": "Put a packed lot on a shipment",
        "description": "Links a packed lot of the shipment's departure facility, whole: every carton of the lot goes on the shipment, with the lot's current seal number and its time. A lot ships once. Audited (`shipment.lot.add`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities); auditor and lab are refused.",
        "tags": [
          "shipping"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "SH-260930-01"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ShipmentLotLink"
              },
              "example": {
                "lot": "LO-260928-014"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The shipment with the lot.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Shipment"
                },
                "example": {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "setpoint_c": 13.0,
                  "tolerance_c": 2.0,
                  "logger_interval_minutes": 15,
                  "logger": {
                    "device_id": "reefer-logger-0731"
                  },
                  "status": "open",
                  "created_by": "shipper@coop.example",
                  "created_at": 1790040000.0,
                  "departed_by": null,
                  "departed_at": null,
                  "lots": [
                    {
                      "lot": "LO-260928-014",
                      "status": "packed",
                      "cartons": 41,
                      "seal_no": "0492117",
                      "sealed_at": 1790040600.0,
                      "current_seal_no": "0492117",
                      "seal_matches": true,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041000.0
                    }
                  ],
                  "logger_check": {
                    "status": "missing",
                    "readings": 0,
                    "considered": 0,
                    "first_at": null,
                    "last_at": null,
                    "min_c": null,
                    "max_c": null,
                    "seal_at": null,
                    "until": null,
                    "gap_count": 0,
                    "gaps": [],
                    "out_of_range_count": 0,
                    "out_of_range": [],
                    "complete": false,
                    "within_setpoint": false
                  },
                  "national_portal": {
                    "rows": 0,
                    "delivered": 0,
                    "pending": 0,
                    "failing": 0,
                    "filed": false
                  },
                  "consignee": null,
                  "documents": [],
                  "paperwork": {
                    "required": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "missing": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "complete": false
                  },
                  "amendments": []
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON or a body that is not exactly a lot code; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: exactly lot",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment or lot for this tenant (another tenant's, or outside an operator's facilities).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The shipment departed or is full, or the lot is at another facility, not packed, has a failed lab result or is already on a shipment. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "shipment_is_departed": {
                    "value": {
                      "error": "shipment is departed",
                      "code": "shipment_is_departed"
                    }
                  },
                  "lot_is_at_another_facility": {
                    "value": {
                      "error": "lot is at another facility: a shipment carries lots of its departure facility",
                      "code": "lot_is_at_another_facility"
                    }
                  },
                  "lot_is_closed": {
                    "value": {
                      "error": "lot is closed: only a packed lot ships",
                      "code": "lot_is_closed"
                    }
                  },
                  "lot_failed_its_lab_test": {
                    "value": {
                      "error": "lot failed its lab test: a lot with a failed lab result does not ship",
                      "code": "lot_failed_its_lab_test"
                    }
                  },
                  "lot_already_on_shipment_sh_260930_01": {
                    "value": {
                      "error": "lot already on shipment SH-260930-01",
                      "code": "lot_already_on_shipment_sh_260930_01"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments/{code}/logger-readings": {
      "post": {
        "operationId": "uploadShipmentLoggerReadings",
        "summary": "Upload a signed logger temperature series",
        "description": "Stores a temperature series of the shipment's independent logger, signed with an active key of the device registry owned by the shipment's logger while that logger is active (a single-trip logger delivers its series after the trip, so it comes as signed uploads, not envelopes; several uploads merge into the shipment's one series by instant). A document that does not verify, names another shipment or logger, or holds a reading later than now is refused and stored nowhere. A stored instant is never overwritten: the same value is skipped, another value is a 409; the same signed content twice is a 409. Then the logger cross-check is recomputed. Audited (`shipment.logger.upload`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities); auditor and lab are refused.",
        "tags": [
          "shipping"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "SH-260930-01"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LoggerSeries"
              },
              "example": {
                "logger": "reefer-logger-0731",
                "shipment": "SH-260930-01",
                "capability": "air.temperature",
                "unit": "Cel",
                "readings": [
                  {
                    "time": "2026-09-30T08:30:00+07:00",
                    "value": 13.1
                  },
                  {
                    "time": "2026-09-30T08:45:00+07:00",
                    "value": 12.9
                  }
                ],
                "sig": {
                  "alg": "ES256",
                  "kid": "reefer-logger-0731.k1",
                  "value": "MEUCIQ..."
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The shipment with the recomputed logger check and the upload.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Shipment"
                },
                "example": {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "setpoint_c": 13.0,
                  "tolerance_c": 2.0,
                  "logger_interval_minutes": 15,
                  "logger": {
                    "device_id": "reefer-logger-0731"
                  },
                  "status": "departed",
                  "created_by": "shipper@coop.example",
                  "created_at": 1790040000.0,
                  "departed_by": "shipper@coop.example",
                  "departed_at": 1790042400.0,
                  "lots": [
                    {
                      "lot": "LO-260928-014",
                      "status": "shipped",
                      "cartons": 41,
                      "seal_no": "0492117",
                      "sealed_at": 1790040600.0,
                      "current_seal_no": "0492117",
                      "seal_matches": true,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041000.0
                    }
                  ],
                  "logger_check": {
                    "status": "matched",
                    "readings": 9,
                    "considered": 9,
                    "first_at": 1790040600.0,
                    "last_at": 1790047800.0,
                    "min_c": 12.6,
                    "max_c": 13.4,
                    "seal_at": 1790040600.0,
                    "until": 1790042400.0,
                    "gap_count": 0,
                    "gaps": [],
                    "out_of_range_count": 0,
                    "out_of_range": [],
                    "complete": true,
                    "within_setpoint": true
                  },
                  "national_portal": {
                    "rows": 386,
                    "delivered": 386,
                    "pending": 0,
                    "failing": 0,
                    "filed": true
                  },
                  "upload": {
                    "id": 1,
                    "readings": 9,
                    "added": 9
                  },
                  "consignee": null,
                  "documents": [],
                  "paperwork": {
                    "required": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "missing": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "complete": false
                  },
                  "amendments": []
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a malformed series, a series that names another shipment or logger, or a signature that does not verify with an active registry key of the shipment's active logger; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_document": {
                    "value": {
                      "error": "invalid document: exactly logger, shipment, capability, unit, readings and sig",
                      "code": "invalid_document"
                    }
                  },
                  "invalid_signature": {
                    "value": {
                      "error": "invalid signature",
                      "code": "invalid_signature"
                    }
                  },
                  "invalid_readings": {
                    "value": {
                      "error": "invalid readings: a reading is later than now",
                      "code": "invalid_readings"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment for this tenant: a shipment of another tenant, or departing a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: SH-260930-01",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The series was uploaded already, a stored instant has another value, or the shipment would hold too many readings. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "logger_series_already_uploaded": {
                    "value": {
                      "error": "logger series already uploaded",
                      "code": "logger_series_already_uploaded"
                    }
                  },
                  "reading_differs": {
                    "value": {
                      "error": "reading differs: a stored instant has another value",
                      "code": "reading_differs"
                    }
                  },
                  "too_many_readings": {
                    "value": {
                      "error": "too many readings: a shipment holds at most 8640",
                      "code": "too_many_readings"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments/{code}/depart": {
      "post": {
        "operationId": "departShipment",
        "summary": "The ship event: the shipment departs",
        "description": "The open shipment departs now: its lots move from packed to shipped in the same transaction and the logger cross-check is recomputed up to the departure. A lot whose lab report failed after it was linked stops the departure (409 `lot_failed_its_lab_test`, #138). A shipment lacking its destination market's required papers does not depart (409 `missing_paperwork`, naming the missing items; CN: the consignee, the phytosanitary certificate and the test report, #153). The departure also takes each departing lot's carton label print check (ADR 0001, #176): if any of the lot's cartons has no carton label print recorded after its contents were last set, or the lot has no carton, the lot's packing step is lowered to Self-declared (trust reason `carton_labels_not_printed`, in GET /v1/lots/{lot}/trust and the public lot record's journey), and the lot's tier with it; a passed check changes nothing, a print recorded after the departure lifts nothing, and the departure is never refused for it. Tenant-entered (no signed ship envelope is emitted: the backend holds no private key). Audited (`shipment.depart`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities); auditor and lab are refused.",
        "tags": [
          "shipping"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "SH-260930-01"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ShipmentDepart"
              },
              "example": {}
            }
          }
        },
        "responses": {
          "200": {
            "description": "The departed shipment.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Shipment"
                },
                "example": {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "setpoint_c": 13.0,
                  "tolerance_c": 2.0,
                  "logger_interval_minutes": 15,
                  "logger": {
                    "device_id": "reefer-logger-0731"
                  },
                  "status": "departed",
                  "created_by": "shipper@coop.example",
                  "created_at": 1790040000.0,
                  "departed_by": "shipper@coop.example",
                  "departed_at": 1790042400.0,
                  "lots": [
                    {
                      "lot": "LO-260928-014",
                      "status": "shipped",
                      "cartons": 41,
                      "seal_no": "0492117",
                      "sealed_at": 1790040600.0,
                      "current_seal_no": "0492117",
                      "seal_matches": true,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041000.0
                    }
                  ],
                  "logger_check": {
                    "status": "matched",
                    "readings": 9,
                    "considered": 9,
                    "first_at": 1790040600.0,
                    "last_at": 1790047800.0,
                    "min_c": 12.6,
                    "max_c": 13.4,
                    "seal_at": 1790040600.0,
                    "until": 1790042400.0,
                    "gap_count": 0,
                    "gaps": [],
                    "out_of_range_count": 0,
                    "out_of_range": [],
                    "complete": true,
                    "within_setpoint": true
                  },
                  "national_portal": {
                    "rows": 386,
                    "delivered": 386,
                    "pending": 0,
                    "failing": 0,
                    "filed": true
                  },
                  "consignee": null,
                  "documents": [],
                  "paperwork": {
                    "required": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "missing": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "complete": false
                  },
                  "amendments": []
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON or a non-empty body; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment for this tenant: a shipment of another tenant, or departing a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: SH-260930-01",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The shipment departed already, carries no lot, a lot is no longer packed or has a failed lab result (#138), or the destination market's required papers are missing (#153). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "shipment_is_departed": {
                    "value": {
                      "error": "shipment is departed",
                      "code": "shipment_is_departed"
                    }
                  },
                  "no_lots": {
                    "value": {
                      "error": "no lots: a shipment departs with at least one packed lot",
                      "code": "no_lots"
                    }
                  },
                  "lot_lo_260928_014_is_shipped": {
                    "value": {
                      "error": "lot LO-260928-014 is shipped",
                      "code": "lot_lo_260928_014_is_shipped"
                    }
                  },
                  "lot_failed_its_lab_test": {
                    "value": {
                      "error": "lot failed its lab test: lot LO-260928-014 has a failed lab result and does not ship",
                      "code": "lot_failed_its_lab_test"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  },
                  "missing_paperwork": {
                    "value": {
                      "error": "missing paperwork: consignee, phytosanitary_certificate, test_report",
                      "code": "missing_paperwork"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "The open shipment departs now: its lots move from packed to shipped in the same transaction and the logger cross-check is recomputed up to the departure. A lot whose lab report failed after it was linked stops the departure (409 `lot_failed_its_lab_test`, #138). A shipment lacking its destination market's required papers does not depart (409 `missing_paperwork`, naming the missing items; CN: the consignee, the phytosanitary certificate and the test report, #153). Tenant-entered (no signed ship envelope is emitted: the backend holds no private key). Audited (`shipment.depart`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities); auditor and lab are refused."
      }
    },
    "/v1/crops": {
      "get": {
        "operationId": "listCrops",
        "summary": "List the crop registry",
        "description": "Every crop of the registry by code, and the configured crops without a registry entry. The crop registry: a lot's `product` and a growing area's `crop` must name a crop of the registry or one of the deployment's configured crops. Durian is the crop the platform started with; other crops' rules are added here once their published source is known. Allowed for platform_admin only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "responses": {
          "200": {
            "description": "The registry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CropList"
                },
                "example": {
                  "items": [
                    {
                      "code": "durian",
                      "names": {
                        "vi": "Sầu riêng",
                        "en": "Durian",
                        "zh-Hans": "榴莲"
                      },
                      "ripeness_scale": "levels_1_to_4",
                      "created_at": 0.0,
                      "updated_at": 0.0
                    }
                  ],
                  "configured": [
                    "coconut",
                    "dragon_fruit",
                    "jackfruit",
                    "mango"
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createCrop",
        "summary": "Add a crop to the registry",
        "description": "A platform admin adds a crop: its code, its names in Vietnamese, English and Simplified Chinese and its ripeness scale (null when it has none). A crop is never deleted. Audited (`crop.create`, in the same transaction). Allowed for platform_admin only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CropCreate"
              },
              "example": {
                "code": "longan",
                "names": {
                  "vi": "Nhãn",
                  "en": "Longan",
                  "zh-Hans": "龙眼"
                },
                "ripeness_scale": null
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The crop added.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Crop"
                },
                "example": {
                  "code": "longan",
                  "names": {
                    "vi": "Nhãn",
                    "en": "Longan",
                    "zh-Hans": "龙眼"
                  },
                  "ripeness_scale": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad code, names or ripeness scale, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: hs_code",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_code": {
                    "value": {
                      "error": "invalid code: 1 to 64 lower-case letters, digits or '_', starting with a letter",
                      "code": "invalid_code"
                    }
                  },
                  "invalid_names": {
                    "value": {
                      "error": "invalid names: an object with the crop's name in vi, en and zh-Hans",
                      "code": "invalid_names"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The crop code is taken, or the registry holds 200 crops. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "crop_code_taken": {
                    "value": {
                      "error": "crop code taken",
                      "code": "crop_code_taken"
                    }
                  },
                  "too_many_crops": {
                    "value": {
                      "error": "too many crops: the registry holds at most 200",
                      "code": "too_many_crops"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/crops/{code}": {
      "get": {
        "operationId": "getCrop",
        "summary": "Get a crop with its rules",
        "description": "A crop of the registry with its rules per destination market (registration protocol and sampling rule) and its grading rules. Allowed for platform_admin only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Crop code.",
            "schema": {
              "type": "string"
            },
            "example": "durian"
          }
        ],
        "responses": {
          "200": {
            "description": "The crop and its rules.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CropDetail"
                },
                "example": {
                  "code": "durian",
                  "names": {
                    "vi": "Sầu riêng",
                    "en": "Durian",
                    "zh-Hans": "榴莲"
                  },
                  "ripeness_scale": "levels_1_to_4",
                  "created_at": 0.0,
                  "updated_at": 0.0,
                  "markets": [
                    {
                      "crop": "durian",
                      "market": "CN",
                      "registration_protocol": true,
                      "sampling": {
                        "rule": "cn-durian-protocol-2022",
                        "rule_source": "https://trungtamwto.vn/thi-truong-duc/21143-sau-rieng-viet-nam-xuat-khau-chinh-ngach-sang-trung-quoc",
                        "base_rate": 0.02,
                        "clean_rate": 0.01,
                        "clean_days": 730,
                        "analytes": [
                          "cadmium",
                          "auramine_o"
                        ],
                        "analytes_source": "https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports"
                      },
                      "created_at": 0.0,
                      "updated_at": 0.0
                    }
                  ],
                  "grading_rules": [
                    {
                      "crop": "durian",
                      "variety": null,
                      "rules": {
                        "a_levels": [
                          2,
                          3
                        ],
                        "reject_levels": [
                          1,
                          4
                        ],
                        "a_weight_kg": [
                          [
                            2.0,
                            5.0
                          ]
                        ],
                        "a_min_confidence": 0.8,
                        "eating_window": [
                          {
                            "band": "ambient",
                            "end_days": 7,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": "immature"
                          },
                          {
                            "band": "ambient",
                            "end_days": 6,
                            "level": 2,
                            "max_days": 1,
                            "min_days": 0,
                            "start_days": 4,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 4,
                            "level": 2,
                            "max_days": 3,
                            "min_days": 2,
                            "start_days": 3,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 2,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 4,
                            "start_days": 1,
                            "warning": "eat_soon"
                          },
                          {
                            "band": "ambient",
                            "end_days": 4,
                            "level": 3,
                            "max_days": 1,
                            "min_days": 0,
                            "start_days": 3,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 3,
                            "level": 3,
                            "max_days": 3,
                            "min_days": 2,
                            "start_days": 2,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 1,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 4,
                            "start_days": 0,
                            "warning": "eat_soon"
                          },
                          {
                            "band": "ambient",
                            "end_days": 1,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          },
                          {
                            "band": "14-18C",
                            "end_days": 10,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 7,
                            "warning": "immature"
                          },
                          {
                            "band": "14-18C",
                            "end_days": 8,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": null
                          },
                          {
                            "band": "14-18C",
                            "end_days": 6,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 4,
                            "warning": null
                          },
                          {
                            "band": "14-18C",
                            "end_days": 2,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          },
                          {
                            "band": "10-13C",
                            "end_days": 12,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 9,
                            "warning": "immature"
                          },
                          {
                            "band": "10-13C",
                            "end_days": 10,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 7,
                            "warning": null
                          },
                          {
                            "band": "10-13C",
                            "end_days": 8,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": null
                          },
                          {
                            "band": "10-13C",
                            "end_days": 2,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          }
                        ]
                      },
                      "created_at": 0.0,
                      "updated_at": 0.0
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such crop in the registry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_found": {
                    "value": {
                      "error": "not found: crops",
                      "code": "not_found"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateCrop",
        "summary": "Edit a crop",
        "description": "A platform admin changes a crop's names or ripeness scale (its code never changes). Audited (`crop.update`, in the same transaction). Allowed for platform_admin only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Crop code.",
            "schema": {
              "type": "string"
            },
            "example": "durian"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CropUpdate"
              },
              "example": {
                "ripeness_scale": "levels_1_to_4"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The crop after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Crop"
                },
                "example": {
                  "code": "longan",
                  "names": {
                    "vi": "Nhãn",
                    "en": "Longan",
                    "zh-Hans": "龙眼"
                  },
                  "ripeness_scale": "levels_1_to_4",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000060.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, nothing to update, an unknown field, a bad value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "nothing_to_update": {
                    "value": {
                      "error": "nothing to update",
                      "code": "nothing_to_update"
                    }
                  },
                  "invalid_ripeness_scale": {
                    "value": {
                      "error": "invalid ripeness_scale: levels_1_to_4 or null (the crop has no ripeness scale)",
                      "code": "invalid_ripeness_scale"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such crop in the registry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_found": {
                    "value": {
                      "error": "not found: crops",
                      "code": "not_found"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/crops/{code}/markets/{market}": {
      "put": {
        "operationId": "putCropMarketRule",
        "summary": "Set a crop's rules for a destination market",
        "description": "A platform admin sets, for one crop and destination market, whether the market's registration protocol applies to the crop and the market's sampling rule (null: none). A lot is sampled under its crop's rule for its destination market (or the crop's only rule when the lot names no market); a crop without a rule is not sampled. The rule id is unique across crops and markets, and the id of a rule lots were sampled under cannot be replaced (its numbers can, for later samplings). Audited (`crop_market_rule.put`, in the same transaction). Allowed for platform_admin only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Crop code.",
            "schema": {
              "type": "string"
            },
            "example": "durian"
          },
          {
            "name": "market",
            "in": "path",
            "required": true,
            "description": "Destination market (ISO 3166-1 alpha-2).",
            "schema": {
              "type": "string"
            },
            "example": "CN"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CropMarketRulePut"
              },
              "example": {
                "registration_protocol": true,
                "sampling": {
                  "rule": "cn-durian-protocol-2022",
                  "rule_source": "https://trungtamwto.vn/thi-truong-duc/21143-sau-rieng-viet-nam-xuat-khau-chinh-ngach-sang-trung-quoc",
                  "base_rate": 0.02,
                  "clean_rate": 0.01,
                  "clean_days": 730,
                  "analytes": [
                    "cadmium",
                    "auramine_o"
                  ],
                  "analytes_source": "https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The crop's rules for the market.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CropMarketRule"
                },
                "example": {
                  "crop": "durian",
                  "market": "CN",
                  "registration_protocol": true,
                  "sampling": {
                    "rule": "cn-durian-protocol-2022",
                    "rule_source": "https://trungtamwto.vn/thi-truong-duc/21143-sau-rieng-viet-nam-xuat-khau-chinh-ngach-sang-trung-quoc",
                    "base_rate": 0.02,
                    "clean_rate": 0.01,
                    "clean_days": 730,
                    "analytes": [
                      "cadmium",
                      "auramine_o"
                    ],
                    "analytes_source": "https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports"
                  },
                  "created_at": 0.0,
                  "updated_at": 0.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown market, an unknown or missing field, a bad value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_market": {
                    "value": {
                      "error": "invalid market: one of CN",
                      "code": "invalid_market"
                    }
                  },
                  "missing_field": {
                    "value": {
                      "error": "missing field: sampling.clean_days",
                      "code": "missing_field"
                    }
                  },
                  "invalid_base_rate": {
                    "value": {
                      "error": "invalid sampling.base_rate: a share above 0 and at most 1 (0.02 is 2%)",
                      "code": "invalid_sampling_base_rate"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such crop in the registry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_found": {
                    "value": {
                      "error": "not found: crops",
                      "code": "not_found"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "Another crop or market uses the rule id, or lots were sampled under the rule id this would replace.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "taken": {
                    "value": {
                      "error": "sampling rule id taken: another crop or market uses it",
                      "code": "sampling_rule_id_taken"
                    }
                  },
                  "recorded": {
                    "value": {
                      "error": "sampling rule recorded: lots were sampled under this rule id; keep the id to edit it",
                      "code": "sampling_rule_recorded"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/crops/{code}/grading-rules": {
      "put": {
        "operationId": "putCropGradingRule",
        "summary": "Set a crop's grading rules",
        "description": "A platform admin sets the platform's grading rules for one variety of a crop, or for every variety of it (`variety` null). A lot is graded by its company's rules for its variety when the company has some, else by these (the variety's, else the crop's), else by the platform default. Audited (`crop_grading_rule.put`, in the same transaction). Allowed for platform_admin only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "registry"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Crop code.",
            "schema": {
              "type": "string"
            },
            "example": "durian"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CropGradingRulePut"
              },
              "example": {
                "variety": null,
                "rules": {
                  "a_levels": [
                    2,
                    3
                  ],
                  "reject_levels": [
                    1,
                    4
                  ],
                  "a_weight_kg": [
                    [
                      2.0,
                      5.0
                    ]
                  ],
                  "a_min_confidence": 0.8,
                  "eating_window": [
                    {
                      "band": "ambient",
                      "end_days": 7,
                      "level": 1,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 5,
                      "warning": "immature"
                    },
                    {
                      "band": "ambient",
                      "end_days": 6,
                      "level": 2,
                      "max_days": 1,
                      "min_days": 0,
                      "start_days": 4,
                      "warning": null
                    },
                    {
                      "band": "ambient",
                      "end_days": 4,
                      "level": 2,
                      "max_days": 3,
                      "min_days": 2,
                      "start_days": 3,
                      "warning": null
                    },
                    {
                      "band": "ambient",
                      "end_days": 2,
                      "level": 2,
                      "max_days": 30,
                      "min_days": 4,
                      "start_days": 1,
                      "warning": "eat_soon"
                    },
                    {
                      "band": "ambient",
                      "end_days": 4,
                      "level": 3,
                      "max_days": 1,
                      "min_days": 0,
                      "start_days": 3,
                      "warning": null
                    },
                    {
                      "band": "ambient",
                      "end_days": 3,
                      "level": 3,
                      "max_days": 3,
                      "min_days": 2,
                      "start_days": 2,
                      "warning": null
                    },
                    {
                      "band": "ambient",
                      "end_days": 1,
                      "level": 3,
                      "max_days": 30,
                      "min_days": 4,
                      "start_days": 0,
                      "warning": "eat_soon"
                    },
                    {
                      "band": "ambient",
                      "end_days": 1,
                      "level": 4,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 0,
                      "warning": "overripe"
                    },
                    {
                      "band": "14-18C",
                      "end_days": 10,
                      "level": 1,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 7,
                      "warning": "immature"
                    },
                    {
                      "band": "14-18C",
                      "end_days": 8,
                      "level": 2,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 5,
                      "warning": null
                    },
                    {
                      "band": "14-18C",
                      "end_days": 6,
                      "level": 3,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 4,
                      "warning": null
                    },
                    {
                      "band": "14-18C",
                      "end_days": 2,
                      "level": 4,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 0,
                      "warning": "overripe"
                    },
                    {
                      "band": "10-13C",
                      "end_days": 12,
                      "level": 1,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 9,
                      "warning": "immature"
                    },
                    {
                      "band": "10-13C",
                      "end_days": 10,
                      "level": 2,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 7,
                      "warning": null
                    },
                    {
                      "band": "10-13C",
                      "end_days": 8,
                      "level": 3,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 5,
                      "warning": null
                    },
                    {
                      "band": "10-13C",
                      "end_days": 2,
                      "level": 4,
                      "max_days": 30,
                      "min_days": 0,
                      "start_days": 0,
                      "warning": "overripe"
                    }
                  ]
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The grading rules stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CropGradingRule"
                },
                "example": {
                  "crop": "durian",
                  "variety": null,
                  "rules": {
                    "a_levels": [
                      2,
                      3
                    ],
                    "reject_levels": [
                      1,
                      4
                    ],
                    "a_weight_kg": [
                      [
                        2.0,
                        5.0
                      ]
                    ],
                    "a_min_confidence": 0.8,
                    "eating_window": [
                      {
                        "band": "ambient",
                        "end_days": 7,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": "immature"
                      },
                      {
                        "band": "ambient",
                        "end_days": 6,
                        "level": 2,
                        "max_days": 1,
                        "min_days": 0,
                        "start_days": 4,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 4,
                        "level": 2,
                        "max_days": 3,
                        "min_days": 2,
                        "start_days": 3,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 2,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 4,
                        "start_days": 1,
                        "warning": "eat_soon"
                      },
                      {
                        "band": "ambient",
                        "end_days": 4,
                        "level": 3,
                        "max_days": 1,
                        "min_days": 0,
                        "start_days": 3,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 3,
                        "level": 3,
                        "max_days": 3,
                        "min_days": 2,
                        "start_days": 2,
                        "warning": null
                      },
                      {
                        "band": "ambient",
                        "end_days": 1,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 4,
                        "start_days": 0,
                        "warning": "eat_soon"
                      },
                      {
                        "band": "ambient",
                        "end_days": 1,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      },
                      {
                        "band": "14-18C",
                        "end_days": 10,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 7,
                        "warning": "immature"
                      },
                      {
                        "band": "14-18C",
                        "end_days": 8,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": null
                      },
                      {
                        "band": "14-18C",
                        "end_days": 6,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 4,
                        "warning": null
                      },
                      {
                        "band": "14-18C",
                        "end_days": 2,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      },
                      {
                        "band": "10-13C",
                        "end_days": 12,
                        "level": 1,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 9,
                        "warning": "immature"
                      },
                      {
                        "band": "10-13C",
                        "end_days": 10,
                        "level": 2,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 7,
                        "warning": null
                      },
                      {
                        "band": "10-13C",
                        "end_days": 8,
                        "level": 3,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 5,
                        "warning": null
                      },
                      {
                        "band": "10-13C",
                        "end_days": 2,
                        "level": 4,
                        "max_days": 30,
                        "min_days": 0,
                        "start_days": 0,
                        "warning": "overripe"
                      }
                    ]
                  },
                  "created_at": 0.0,
                  "updated_at": 0.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown or missing field, invalid rules, a bad variety, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_rules": {
                    "value": {
                      "error": "invalid rules: a_weight_kg bands must not overlap",
                      "code": "invalid_rules"
                    }
                  },
                  "invalid_variety": {
                    "value": {
                      "error": "invalid variety: a string of 1 to 64 characters",
                      "code": "invalid_variety"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such crop in the registry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_found": {
                    "value": {
                      "error": "not found: crops",
                      "code": "not_found"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The crop already holds 50 other grading rules.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "too_many": {
                    "value": {
                      "error": "too many grading rules: a crop holds at most 50",
                      "code": "too_many_grading_rules"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs": {
      "get": {
        "operationId": "listLabs",
        "summary": "Lab partners",
        "description": "Labs ordered by code, with keyset pagination (at most 100 per page). Allowed for platform_admin (every lab) and for a lab user signed in with a session (its own lab only; another lab answers 404 like a missing one). A lab principal without a lab (an API token) is refused 403. Not audited (a read).",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IkxBQi1WTi0xMTgifQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of labs.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabPage"
                },
                "example": {
                  "items": [
                    {
                      "code": "LAB-VN-118",
                      "name": "Phòng thử nghiệm mẫu",
                      "accreditation": "VILAS 118 (ISO/IEC 17025)",
                      "valid_to": "2027-12-31",
                      "status": "active",
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5,
                      "in_force": true,
                      "accreditation_body": "BoA (VILAS)",
                      "accreditation_number": "VILAS 118",
                      "accreditation_scope": "Cadmium (ICP-MS) and auramine O (LC-MS/MS) in fresh fruit"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createLab",
        "summary": "Register a lab partner",
        "description": "Registers an accredited lab (status active). A taken code is 409. Audited (`lab.create`). Allowed for platform_admin.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabCreate"
              },
              "example": {
                "code": "LAB-VN-118",
                "name": "Phòng thử nghiệm mẫu",
                "accreditation": "VILAS 118 (ISO/IEC 17025)",
                "valid_to": "2027-12-31"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Lab"
                },
                "example": {
                  "code": "LAB-VN-118",
                  "name": "Phòng thử nghiệm mẫu",
                  "accreditation": "VILAS 118 (ISO/IEC 17025)",
                  "valid_to": "2027-12-31",
                  "status": "active",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "in_force": true,
                  "accreditation_body": "BoA (VILAS)",
                  "accreditation_number": "VILAS 118",
                  "accreditation_scope": "Cadmium (ICP-MS) and auramine O (LC-MS/MS) in fresh fruit"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad code, name, accreditation or valid_to, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_code": {
                    "value": {
                      "error": "invalid code: LAB-<country>-<id>, e.g. LAB-VN-118",
                      "code": "invalid_code"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lab code is taken. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lab_code_taken": {
                    "value": {
                      "error": "lab code taken",
                      "code": "lab_code_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}": {
      "get": {
        "operationId": "getLab",
        "summary": "A lab partner",
        "description": "One lab. Allowed for platform_admin (every lab) and for a lab user signed in with a session (its own lab only; another lab answers 404 like a missing one). A lab principal without a lab (an API token) is refused 403. Not audited (a read).",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          }
        ],
        "responses": {
          "200": {
            "description": "The lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Lab"
                },
                "example": {
                  "code": "LAB-VN-118",
                  "name": "Phòng thử nghiệm mẫu",
                  "accreditation": "VILAS 118 (ISO/IEC 17025)",
                  "valid_to": "2027-12-31",
                  "status": "active",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "in_force": true,
                  "accreditation_body": "BoA (VILAS)",
                  "accreditation_number": "VILAS 118",
                  "accreditation_scope": "Cadmium (ICP-MS) and auramine O (LC-MS/MS) in fresh fruit"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab, or a lab outside the caller's scope (a lab user's other labs).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateLab",
        "summary": "Edit or suspend a lab partner",
        "description": "Changes name, accreditation, valid_to or status (active or suspended; a suspended lab is not assigned samples). Audited (`lab.update`). Allowed for platform_admin.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabUpdate"
              },
              "example": {
                "status": "suspended"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The lab after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Lab"
                },
                "example": {
                  "code": "LAB-VN-118",
                  "name": "Phòng thử nghiệm mẫu",
                  "accreditation": "VILAS 118 (ISO/IEC 17025)",
                  "valid_to": "2027-12-31",
                  "status": "suspended",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5,
                  "in_force": false,
                  "accreditation_body": "BoA (VILAS)",
                  "accreditation_number": "VILAS 118",
                  "accreditation_scope": "Cadmium (ICP-MS) and auramine O (LC-MS/MS) in fresh fruit"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, nothing to update, an unknown field, a bad value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_status": {
                    "value": {
                      "error": "invalid status: active or suspended",
                      "code": "invalid_status"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab, or a lab outside the caller's scope (a lab user's other labs).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/keys": {
      "get": {
        "operationId": "listLabKeys",
        "summary": "A lab's signing keys",
        "description": "Keys ordered by kid, with keyset pagination (at most 100 per page). Never returns key material, only fingerprints. Allowed for platform_admin (every lab) and for a lab user signed in with a session (its own lab only; another lab answers 404 like a missing one). A lab principal without a lab (an API token) is refused 403. Not audited (a read).",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IkxBQi1WTi0xMTgifQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of keys.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabKeyPage"
                },
                "example": {
                  "items": [
                    {
                      "kid": "LAB-VN-118.2026",
                      "lab": "LAB-VN-118",
                      "status": "active",
                      "created_at": 1790000000.5,
                      "revoked_at": null,
                      "revoke_reason": null,
                      "revoked_by": null,
                      "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                      "fingerprint": "19fc…e0d9",
                      "custody": "lab"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab, or a lab outside the caller's scope (a lab user's other labs).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createLabKey",
        "summary": "Register a lab signing key",
        "description": "Registers an active EC P-256 public key of the lab. Key ids share one namespace with device and gateway keys: a taken or reserved kid is 409. Audited (`lab_key.create`; the PEM is never copied into the audit row). Allowed for platform_admin (every lab) and for a lab user signed in with a session (its own lab only; another lab answers 404 like a missing one). A lab principal without a lab (an API token) is refused 403.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabKeyCreate"
              },
              "example": {
                "kid": "LAB-VN-118.2026",
                "public_key_pem": "-----BEGIN PUBLIC KEY-----\n…\n-----END PUBLIC KEY-----\n"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabKey"
                },
                "example": {
                  "kid": "LAB-VN-118.2026",
                  "lab": "LAB-VN-118",
                  "status": "active",
                  "created_at": 1790000000.5,
                  "revoked_at": null,
                  "revoke_reason": null,
                  "revoked_by": null,
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "custody": "lab"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad kid or public key, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_pem": {
                    "value": {
                      "error": "invalid public_key_pem: an EC P-256 public key as PEM SubjectPublicKeyInfo",
                      "code": "invalid_public_key_pem"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab, or a lab outside the caller's scope (a lab user's other labs).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The key id is taken (by any key) or reserved. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_id_taken": {
                    "value": {
                      "error": "key id taken",
                      "code": "key_id_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/keys/{kid}/revoke": {
      "post": {
        "operationId": "revokeLabKey",
        "summary": "Revoke a lab signing key",
        "description": "Marks the key revoked with its reason; a revoked key cannot be revoked again (the first reason and time stay). `compromise` also raises one high-severity `lab_key_compromised` platform alert. Audited (`lab_key.revoke`). Allowed for platform_admin (every lab) and for a lab user signed in with a session (its own lab only; another lab answers 404 like a missing one). A lab principal without a lab (an API token) is refused 403. Step-up (#87): a signed-in session of an account with two-step sign-in must have confirmed a code from its authenticator app (or a backup code) within the last 5 minutes and its password within the last 10 minutes, else 401 `mfa_step_up_required` before anything is done (no audit row): confirm both with POST /v1/auth/reauth, then repeat the request. A session of an account without two-step sign-in, API tokens and API clients are served as before.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "name": "kid",
            "in": "path",
            "required": true,
            "description": "Key id.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118.2026"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/KeyRevoke"
              },
              "example": {
                "reason": "rotation"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The key after revocation.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabKey"
                },
                "example": {
                  "kid": "LAB-VN-118.2026",
                  "lab": "LAB-VN-118",
                  "status": "revoked",
                  "created_at": 1790000000.5,
                  "revoked_at": 1790086400.5,
                  "revoke_reason": "rotation",
                  "revoked_by": "lab@lab.example",
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "custody": "lab"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a reason other than rotation or compromise, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: rotation or compromise",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            },
            "x-sdk-description": "No valid session, API token or legacy token."
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab in the caller's scope, or no such key of the lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The key is already revoked. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_already_revoked": {
                    "value": {
                      "error": "key already revoked",
                      "code": "key_already_revoked"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Marks the key revoked with its reason; a revoked key cannot be revoked again (the first reason and time stay). `compromise` also raises one high-severity `lab_key_compromised` platform alert. Audited (`lab_key.revoke`). Allowed for platform_admin (every lab) and for a lab user signed in with a session (its own lab only; another lab answers 404 like a missing one). A lab principal without a lab (an API token) is refused 403."
      }
    },
    "/v1/labs/{code}/logins": {
      "get": {
        "operationId": "listLabLogins",
        "summary": "A lab's logins and pending invitations",
        "description": "#283. The people who sign in for the lab on the lab portal and the lab's pending invitations; never a link or its token (`no-store`). Not audited (a read). Allowed for platform_admin through a signed-in session only: a lab login sees every sampling assigned to its lab, for every company, so a company admin never lists or makes one. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the platform admin console's lab page.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          }
        ],
        "responses": {
          "200": {
            "description": "The lab's logins.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabLogins"
                },
                "example": {
                  "members": [
                    {
                      "email": "analyst@lab-vn-118.example",
                      "display_name": "Chi Hoa",
                      "status": "active",
                      "since": 1790000000.5
                    }
                  ],
                  "invitations": [
                    {
                      "id": 31,
                      "email": "second@lab-vn-118.example",
                      "display_name": null,
                      "created_at": 1790100000.5,
                      "created_by": "ops@croppath.example",
                      "expires_at": 1790359200.5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused; a company admin never manages a lab's logins), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-404",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/invitations": {
      "post": {
        "operationId": "createLabInvitation",
        "summary": "Invite a lab analyst (link shown once)",
        "description": "#283. Creates a one-time link that lets the person with `email` choose a password and sign in for the lab on the lab portal (or, when the email has an account that is already this lab's login, only confirm it). The link is returned once (`no-store`) and works once, for 72 hours, unless revoked; only the SHA-256 of its token is stored. The login belongs to the company record kept only for lab logins (`croppath-labs`, created with the first invitation), never to a customer company: an email whose account holds any other membership is refused 409 `lab_account_must_be_separate`, and a company's invitation never reaches a lab login made this way. The lab must exist and be active, when the link is made and when it is accepted. Audited (`account_link.create`, in the same transaction, in the lab logins' company's log: purpose, role, lab, expiry; never the link). Allowed for platform_admin through a signed-in session only; the session must have confirmed its password within the last 10 minutes (SELF-1-2), else 401 `reauthentication_required` before anything is done. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the platform admin console's lab page.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabInvitationCreate"
              },
              "example": {
                "email": "analyst@lab-vn-118.example",
                "display_name": "Chi Hoa"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The link, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountLinkCreated"
                },
                "example": {
                  "id": 31,
                  "link": "https://txng.theio.vn/login#invite=agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
                  "expires_at": 1790359200.5,
                  "emailed": false
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad email or display name, or a bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the link, whose token is never stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "email": {
                    "value": {
                      "error": "invalid email",
                      "code": "invalid_email"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: role",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused; a company admin never manages a lab's logins), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-404",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lab is suspended; the email's account holds another membership (a company's member, a platform admin or another lab's login), already signs in for this lab, or its login for this lab was turned off by CropPath support (who turns it back on); or a cap of this lab's links is reached: at most 50 pending links, and 30 new links an hour, counted for each lab on its own (another lab's links never count).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "suspended": {
                    "value": {
                      "error": "lab suspended: turn the lab back on before inviting anyone",
                      "code": "lab_suspended"
                    }
                  },
                  "separate": {
                    "value": {
                      "error": "lab account must be separate: a lab login signs in for one lab and for no company",
                      "code": "lab_account_must_be_separate"
                    }
                  },
                  "member": {
                    "value": {
                      "error": "already a member: this person already signs in for this lab",
                      "code": "already_a_member"
                    }
                  },
                  "turned_off": {
                    "value": {
                      "error": "lab login turned off: CropPath support turns it back on",
                      "code": "lab_login_turned_off"
                    }
                  },
                  "pending": {
                    "value": {
                      "error": "too many pending links: at most 50 per lab",
                      "code": "too_many_pending_links"
                    }
                  },
                  "hourly": {
                    "value": {
                      "error": "too many links: at most 30 per lab per hour",
                      "code": "too_many_links"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/labs/{code}/invitations/{id}/revoke": {
      "post": {
        "operationId": "revokeLabInvitation",
        "summary": "Revoke a lab's pending invitation",
        "description": "#283. The lab's invitation stops working at once. Audited (`account_link.revoke`, in the same transaction, in the lab logins' company's log, with the link's purpose and lab). Turning a lab login off stays with CropPath support. Allowed for platform_admin through a signed-in session only: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the platform admin console's lab page.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The invitation's id (from listLabLogins).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The invitation, revoked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvitationRevoked"
                },
                "example": {
                  "id": 12,
                  "status": "revoked"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused; a company admin never manages a lab's logins), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No pending invitation of this lab with this id (used, revoked, expired, another lab's or no lab invitation), or no such lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 31",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/lots/{lot}/samples": {
      "get": {
        "operationId": "getLotSampling",
        "summary": "A lot's sampling",
        "description": "The lot's sampling, or `{\"sampling\": null}` when it was not sampled. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's sampling.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotSamplingRead"
                },
                "example": {
                  "sampling": {
                    "lot": "LO-260928-014",
                    "lab": {
                      "code": "LAB-VN-118",
                      "name": "Phòng thử nghiệm mẫu"
                    },
                    "rule": {
                      "id": "cn-durian-protocol-2022",
                      "source": "https://trungtamwto.vn/thi-truong-duc/21143-sau-rieng-viet-nam-xuat-khau-chinh-ngach-sang-trung-quoc",
                      "base_rate": 0.02,
                      "risk_score": 1.0,
                      "rate": 0.02,
                      "factors": {
                        "clean_history": false,
                        "override_share": 0.0234,
                        "high_overrides": false,
                        "over_quota": false,
                        "low_headroom": false
                      }
                    },
                    "population": 123,
                    "sample_count": 3,
                    "analytes": [
                      "cadmium",
                      "auramine_o"
                    ],
                    "selected_by": "operator@coop.example",
                    "selected_at": 1790000000.5,
                    "samples": [
                      {
                        "k": 1,
                        "fruit": "Q-014-0017",
                        "status": "selected"
                      },
                      {
                        "k": 2,
                        "fruit": "Q-014-0062",
                        "status": "selected"
                      },
                      {
                        "k": 3,
                        "fruit": "Q-014-0109",
                        "status": "selected"
                      }
                    ],
                    "report": null
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "sampleLot",
        "summary": "Select a lot's samples and assign a lab",
        "description": "Takes no input: the system decides how many fruits are sampled, which ones and which lab tests them, so a tenant cannot pick the samples. Rule: the sampling rule of the lot's crop (its product) for its destination market, or the crop's only rule when the lot's destination names no market; a crop without one (or with rules for several markets and no destination naming one) is not sampled (409 no sampling rule). Durian has the China durian protocol. Count: the rule's rate (for durian, 2% of the consignment, the lot's export fruits; 1% after two years of the growing area without a failed sample) times a risk score from the deployment's sampling policy (sensory override share, the growing area's volume headroom), rounded up, at least 1 and at most 50. The fruits are drawn with a CSPRNG, and the lab the same way, only among the labs that serve the lot's company (#278: a platform admin links a lab to the companies it serves, `linkLabCompany`; a lab without a link serves no company); when no lab in force with an active key serves it, the lot is not sampled (409 no lab serves this company; 409 no accredited lab available when no lab is in force at all). D15 (#322): for a market whose official approved-lab list the deployment imports (AGRITRACE_LAB_LIST_MARKETS), the lab is drawn only among those labs whose current approvals for that market (valid today in Asia/Ho_Chi_Minh) together cover every analyte of the rule; when none does, the lot is not sampled (409 no approved lab available). For any other market the lab is drawn among every lab in force with an active key that serves the company, and the fallback is logged as a warning. Test scope: the rule's analytes (for durian, cadmium and auramine O). Needs a lot that is open, paused, closed or packed, with no open or paused measurement session, no fruit in review (`pending_review`) and, while the lot is open, none awaiting a device measurement (`awaiting_device`) (409 lot not settled otherwise, since a review decision or a late envelope could still move it into or out of the population; on a paused, closed or packed lot no envelope binds and no fruit action applies, so an unmeasured fruit is final and stays outside the population) and at least one export fruit; a lot is sampled once (a second request is 409, nothing is overwritten). The sampling freezes the lot's fruits: afterwards, even while the lot is open, a new measurement session on the lot and every fruit action on its fruits are 409 lot sampled, a device envelope for one of its fruits is stored but not bound (alert lot_sampled), and a review of an envelope bound to one of them changes only the envelope's status (alert lot_sampled), so the recorded population and the drawn fruits keep the state they were sampled in. The sample statuses change later with the lab's results. Audited (`lot.sample`, with how the lab was drawn: `lab_draw` `approved_list` or `any_lab`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only the lots of its facilities).",
        "x-sdk-description": "Takes no input: the system decides how many fruits are sampled, which ones and which lab tests them, so a tenant cannot pick the samples. Count: the China durian protocol rate (2% of the consignment, the lot's export fruits; 1% after two years of the growing area without a failed sample) times a risk score from the deployment's sampling policy (sensory override share, the growing area's volume headroom), rounded up, at least 1 and at most 50. The fruits are drawn with a CSPRNG; the lab is drawn among the labs in force that hold an active key. Test scope: cadmium and auramine O. Needs a lot that is open, paused, closed or packed, with no open or paused measurement session, no fruit in review (`pending_review`) and, while the lot is open, none awaiting a device measurement (`awaiting_device`) (409 lot not settled otherwise, since a review decision or a late envelope could still move it into or out of the population; on a paused, closed or packed lot no envelope binds and no fruit action applies, so an unmeasured fruit is final and stays outside the population) and at least one export fruit; a lot is sampled once (a second request is 409, nothing is overwritten). The sampling freezes the lot's fruits: afterwards, even while the lot is open, a new measurement session on the lot and every fruit action on its fruits are 409 lot sampled, a device envelope for one of its fruits is stored but not bound (alert lot_sampled), and a review of an envelope bound to one of them changes only the envelope's status (alert lot_sampled), so the recorded population and the drawn fruits keep the state they were sampled in. The sample statuses change later with the lab's results. Audited (`lot.sample`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only the lots of its facilities).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "201": {
            "description": "The new sampling.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotSampling"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "lab": {
                    "code": "LAB-VN-118",
                    "name": "Phòng thử nghiệm mẫu"
                  },
                  "rule": {
                    "id": "cn-durian-protocol-2022",
                    "source": "https://trungtamwto.vn/thi-truong-duc/21143-sau-rieng-viet-nam-xuat-khau-chinh-ngach-sang-trung-quoc",
                    "base_rate": 0.02,
                    "risk_score": 1.0,
                    "rate": 0.02,
                    "factors": {
                      "clean_history": false,
                      "override_share": 0.0234,
                      "high_overrides": false,
                      "over_quota": false,
                      "low_headroom": false
                    }
                  },
                  "population": 123,
                  "sample_count": 3,
                  "analytes": [
                    "cadmium",
                    "auramine_o"
                  ],
                  "selected_by": "operator@coop.example",
                  "selected_at": 1790000000.5,
                  "samples": [
                    {
                      "k": 1,
                      "fruit": "Q-014-0017",
                      "status": "selected"
                    },
                    {
                      "k": 2,
                      "fruit": "Q-014-0062",
                      "status": "selected"
                    },
                    {
                      "k": 3,
                      "fruit": "Q-014-0109",
                      "status": "selected"
                    }
                  ],
                  "report": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, any field in the body (sampling takes no input), a lot with more export fruits than the policy bound, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: sampling takes no input",
                      "code": "unknown_field"
                    }
                  },
                  "too_large": {
                    "value": {
                      "error": "lot too large to sample: more than 50000 export fruits",
                      "code": "lot_too_large_to_sample"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot cannot be sampled now. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "sampled": {
                    "value": {
                      "error": "lot already sampled",
                      "code": "lot_already_sampled"
                    }
                  },
                  "measuring": {
                    "value": {
                      "error": "lot has an active measurement session",
                      "code": "lot_has_an_active_measurement_session"
                    }
                  },
                  "unsettled": {
                    "value": {
                      "error": "lot not settled: a fruit awaits a device measurement or a review; measure, reject or review it before sampling",
                      "code": "lot_not_settled"
                    }
                  },
                  "empty": {
                    "value": {
                      "error": "lot has no export fruits to sample",
                      "code": "lot_has_no_export_fruits_to_sample"
                    }
                  },
                  "status": {
                    "value": {
                      "error": "lot status draft does not allow sampling",
                      "code": "lot_status_draft_does_not_allow_sampling"
                    }
                  },
                  "no_lab": {
                    "value": {
                      "error": "no accredited lab available",
                      "code": "no_accredited_lab_available"
                    }
                  },
                  "no_lab_for_company": {
                    "value": {
                      "error": "no lab serves this company: none in force with an active key is linked to it; a platform admin links one",
                      "code": "no_lab_serves_this_company"
                    }
                  },
                  "no_approved_lab": {
                    "value": {
                      "error": "no approved lab available: none in force is approved for CN for cadmium, auramine_o today",
                      "code": "no_approved_lab_available"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "The lot cannot be sampled now. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                },
                "Retry-After": {
                  "$ref": "#/components/headers/Retry-After"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "sampled": {
                      "value": {
                        "error": "lot already sampled",
                        "code": "lot_already_sampled"
                      }
                    },
                    "measuring": {
                      "value": {
                        "error": "lot has an active measurement session",
                        "code": "lot_has_an_active_measurement_session"
                      }
                    },
                    "unsettled": {
                      "value": {
                        "error": "lot not settled: a fruit awaits a device measurement or a review; measure, reject or review it before sampling",
                        "code": "lot_not_settled"
                      }
                    },
                    "empty": {
                      "value": {
                        "error": "lot has no export fruits to sample",
                        "code": "lot_has_no_export_fruits_to_sample"
                      }
                    },
                    "status": {
                      "value": {
                        "error": "lot status draft does not allow sampling",
                        "code": "lot_status_draft_does_not_allow_sampling"
                      }
                    },
                    "no_lab": {
                      "value": {
                        "error": "no accredited lab available",
                        "code": "no_accredited_lab_available"
                      }
                    },
                    "idempotency_key_in_use": {
                      "value": {
                        "error": "idempotency key in use: retry later",
                        "code": "idempotency_key_in_use"
                      }
                    },
                    "idempotency_key_used": {
                      "value": {
                        "error": "idempotency key used: the response is too large to replay",
                        "code": "idempotency_key_used"
                      }
                    },
                    "idempotency_key_unrecorded": {
                      "value": {
                        "error": "idempotency key used: the request ran but its response was not recorded",
                        "code": "idempotency_key_used"
                      }
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/residue-certificate": {
      "get": {
        "operationId": "getLotResidueCertificate",
        "summary": "A lot's residue certificate",
        "description": "#157: every analyte the lot's lab report tested, with its result, the limit of the lot's destination market, where that limit comes from and the verdict, for staff to hand to a buyer. The destination market (`market_from`) is the lot's shipment's destination once the lot is on a shipment, else the lot's own destination when it names a market, else the market of the lab report. For the report's own market each analyte keeps the limit copied onto its results when the lab report was stored; for another market the limit is that market's entry for the lot's product on the report's signed date (`limits_on`, Asia/Ho_Chi_Minh), else the market's default limit rule for pesticides (`basis` default_limit: Japan's and Korea's uniform 0.01 mg/kg, the EU's default of Regulation (EC) No 396/2005 Art. 18(1)(b), and in the United States a residue without a tolerance is not permitted). The default rule applies only to a pesticide that a source the platform has read shows the market sets no specific limit for in the lot's product; otherwise the analyte has no limit. It never applies to a contaminant such as cadmium or to auramine O. Limits are read on the report's signed date, so a limit the platform records later never judges a report signed before it takes effect. An analyte passes when every sample's result passes (a detection limit above a maximum cannot show compliance; a banned substance passes only when not detected); `no_limit` when the market sets none. `required_analytes` are the analytes the destination market's sampling rule for the lot's crop requires, `missing_analytes` those the lab did not test. The certificate's `verdict`: fail when an analyte fails, else incomplete when an analyte has no limit, a required analyte is missing or the lab key that signed the report has been revoked for compromise (`report.key_revoked_for_compromise`: the report then counts as unsigned, as on the public lot record, so it never earns pass), else pass; all null and empty while the lab has not reported. Never on the public record (owner decision: staff and buyers only; buyers have no account yet). An audited read (`export.residue_certificate`: the market, the verdict and the analyte counts), downloaded as an attachment (`Content-Disposition`), never cached. Allowed for tenant_admin, platform_admin acting for the tenant and auditor; operators and labs are refused; another tenant's lot answers like a missing one. An OAuth2 access token needs the `records_export` scope. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "labs"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "records_export"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The residue certificate (ResidueCertificate).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Content-Disposition": {
                "description": "attachment; filename=\"residue-certificate-{lot}.json\"",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ResidueCertificate"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "product": "durian",
                  "report": {
                    "report_no": "KN-260929-0071",
                    "lab": "LAB-VN-118",
                    "market": "CN",
                    "signed_at": 1790671200.0,
                    "received_at": 1790671260.0,
                    "key_custody": "lab",
                    "key_revoked_for_compromise": false
                  },
                  "market": "CN",
                  "market_from": "report",
                  "limits_on": "2026-09-29",
                  "verdict": "pass",
                  "analytes": [
                    {
                      "analyte": "cadmium",
                      "samples": 3,
                      "outcome": "measured",
                      "value": 0.018,
                      "lod": null,
                      "unit": "mg/kg",
                      "limit": {
                        "kind": "max",
                        "value": 0.05,
                        "unit": "mg/kg",
                        "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)",
                        "basis": "market_limit"
                      },
                      "verdict": "pass"
                    },
                    {
                      "analyte": "auramine_o",
                      "samples": 3,
                      "outcome": "not_detected",
                      "value": null,
                      "lod": 0.001,
                      "unit": "mg/kg",
                      "limit": {
                        "kind": "banned",
                        "value": null,
                        "unit": "mg/kg",
                        "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted",
                        "basis": "market_limit"
                      },
                      "verdict": "pass"
                    }
                  ],
                  "required_analytes": [
                    "cadmium",
                    "auramine_o"
                  ],
                  "missing_analytes": []
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lab/samples": {
      "get": {
        "operationId": "listLabAssignments",
        "summary": "The caller lab's sample assignments",
        "description": "The samplings assigned to the caller's lab across every tenant, newest first, with keyset pagination (at most 50 per page): exporter, lot, facility, test scope and the fruits to collect. Allowed for a lab user signed in with a session (its lab only); every other role, and a lab principal without a lab (an API token), is refused 403. Not audited (a read).",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6NDF9"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 50.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50,
              "default": 20
            },
            "example": 20
          }
        ],
        "responses": {
          "200": {
            "description": "One page of assignments.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabAssignmentPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 41,
                      "exporter": "HTX Ngũ Hiệp",
                      "lot": {
                        "code": "LO-260928-014",
                        "product": "durian",
                        "variety": "Ri6",
                        "harvest_date": "2026-09-27"
                      },
                      "facility": {
                        "code": "VN-TGPH-021",
                        "name": "Cơ sở đóng gói Tân Phú",
                        "address": null,
                        "province": "Tiền Giang",
                        "district": "Cai Lậy"
                      },
                      "analytes": [
                        "cadmium",
                        "auramine_o"
                      ],
                      "sample_count": 3,
                      "selected_at": 1790000000.5,
                      "samples": [
                        {
                          "k": 1,
                          "fruit": "Q-014-0017",
                          "status": "selected"
                        },
                        {
                          "k": 2,
                          "fruit": "Q-014-0062",
                          "status": "selected"
                        },
                        {
                          "k": 3,
                          "fruit": "Q-014-0109",
                          "status": "selected"
                        }
                      ],
                      "report": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lab/samples/{id}/results": {
      "post": {
        "operationId": "submitLabReport",
        "summary": "Submit the signed lab report of an assigned sampling",
        "description": "The assigned lab's report for one of its samplings (the `id` of `GET /v1/lab/samples`): a document signed with an active key of that lab (`LabReportSubmission`). The server verifies the signature against the registered key, judges every result against the market's limits (China: cadmium at most 0.05 mg/kg, GB 2762-2022; auramine O banned), and any optional origin isotope result by its region match (a mismatch fails), and stores the report once: each drawn sample becomes `passed` or `failed`, and a failing report raises a high-severity `lab_result_failed` alert for the lot's tenant and puts the lot on hold on its public record. Audited (`lab_report.submit`). Allowed only for a lab user signed in with a session, for its own lab's samplings (another lab's sampling answers 404 like a missing one); every other role, and a lab principal without a lab (an API token), is refused 403, so a tenant can never submit a result for its own lot.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Sampling id, as `GET /v1/lab/samples` lists it.",
            "schema": {
              "type": "string"
            },
            "example": "41"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabReportSubmission"
              },
              "example": {
                "v": 1,
                "lab": "LAB-VN-118",
                "sampling": 41,
                "report_no": "KN-260929-0071",
                "signed_at": "2026-09-29T15:40:00+07:00",
                "report_sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
                "results": [
                  {
                    "sample": 1,
                    "analyte": "cadmium",
                    "outcome": "measured",
                    "value": 0.018,
                    "unit": "mg/kg",
                    "lod": 0.002,
                    "method": "ICP-MS"
                  },
                  {
                    "sample": 1,
                    "analyte": "auramine_o",
                    "outcome": "not_detected",
                    "unit": "mg/kg",
                    "lod": 0.001,
                    "method": "LC-MS/MS"
                  },
                  {
                    "sample": 2,
                    "analyte": "cadmium",
                    "outcome": "measured",
                    "value": 0.018,
                    "unit": "mg/kg",
                    "lod": 0.002,
                    "method": "ICP-MS"
                  },
                  {
                    "sample": 2,
                    "analyte": "auramine_o",
                    "outcome": "not_detected",
                    "unit": "mg/kg",
                    "lod": 0.001,
                    "method": "LC-MS/MS"
                  },
                  {
                    "sample": 3,
                    "analyte": "cadmium",
                    "outcome": "measured",
                    "value": 0.018,
                    "unit": "mg/kg",
                    "lod": 0.002,
                    "method": "ICP-MS"
                  },
                  {
                    "sample": 3,
                    "analyte": "auramine_o",
                    "outcome": "not_detected",
                    "unit": "mg/kg",
                    "lod": 0.001,
                    "method": "LC-MS/MS"
                  }
                ],
                "sig": {
                  "alg": "ES256",
                  "kid": "LAB-VN-118.2026",
                  "value": "oXJnReuBsgt-B5Q50XZIMc1f4ZyKrNbBmGQGqNG_AlzMknHMQA6jRzDDnLYMSR2xQ4fONFxUvflGduCSkSCgTg"
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The stored report.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabReport"
                },
                "example": {
                  "report_no": "KN-260929-0071",
                  "lab": "LAB-VN-118",
                  "kid": "LAB-VN-118.2026",
                  "key_custody": "lab",
                  "market": "CN",
                  "signed_at": 1790671200.0,
                  "report_sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
                  "passed": true,
                  "analytes": [
                    {
                      "analyte": "auramine_o",
                      "passed": true
                    },
                    {
                      "analyte": "cadmium",
                      "passed": true
                    }
                  ],
                  "results": [
                    {
                      "sample": 1,
                      "analyte": "auramine_o",
                      "outcome": "not_detected",
                      "value": null,
                      "unit": "mg/kg",
                      "lod": 0.001,
                      "method": "LC-MS/MS",
                      "limit": {
                        "kind": "banned",
                        "value": null,
                        "unit": "mg/kg",
                        "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 1,
                      "analyte": "cadmium",
                      "outcome": "measured",
                      "value": 0.018,
                      "unit": "mg/kg",
                      "lod": 0.002,
                      "method": "ICP-MS",
                      "limit": {
                        "kind": "max",
                        "value": 0.05,
                        "unit": "mg/kg",
                        "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 2,
                      "analyte": "auramine_o",
                      "outcome": "not_detected",
                      "value": null,
                      "unit": "mg/kg",
                      "lod": 0.001,
                      "method": "LC-MS/MS",
                      "limit": {
                        "kind": "banned",
                        "value": null,
                        "unit": "mg/kg",
                        "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 2,
                      "analyte": "cadmium",
                      "outcome": "measured",
                      "value": 0.018,
                      "unit": "mg/kg",
                      "lod": 0.002,
                      "method": "ICP-MS",
                      "limit": {
                        "kind": "max",
                        "value": 0.05,
                        "unit": "mg/kg",
                        "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 3,
                      "analyte": "auramine_o",
                      "outcome": "not_detected",
                      "value": null,
                      "unit": "mg/kg",
                      "lod": 0.001,
                      "method": "LC-MS/MS",
                      "limit": {
                        "kind": "banned",
                        "value": null,
                        "unit": "mg/kg",
                        "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 3,
                      "analyte": "cadmium",
                      "outcome": "measured",
                      "value": 0.018,
                      "unit": "mg/kg",
                      "lod": 0.002,
                      "method": "ICP-MS",
                      "limit": {
                        "kind": "max",
                        "value": 0.05,
                        "unit": "mg/kg",
                        "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
                      },
                      "passed": true
                    }
                  ],
                  "origin": [],
                  "submitted_by": "lab@lab.example",
                  "received_at": 1790671260.5,
                  "report_pdf": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a missing or unknown member, a result outside the sampling or an incomplete report, a bad value, unit or detection limit, a bad origin result (outcome, region), a signed_at before the draw or in the future, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "incomplete": {
                    "value": {
                      "error": "incomplete results: no cadmium result for sample 3 (1 missing)",
                      "code": "incomplete_results"
                    }
                  },
                  "unit": {
                    "value": {
                      "error": "invalid results[0].unit: mg/kg",
                      "code": "invalid_results_0_unit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session or token, or the report is unsigned or its signature does not verify with an active key of the assigned lab (unknown or revoked key, another lab's key, altered content).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "token": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "signature": {
                    "value": {
                      "error": "signature not verified: sign the report with an active key of the assigned lab",
                      "code": "signature_not_verified"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the sampling's company is leaving CropPath or has left, whatever company the lab user belongs to; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sampling, or one assigned to another lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 41",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The sampling already has a report (nothing is overwritten), the lab's report number is taken, or the lab is not in force. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "reported": {
                    "value": {
                      "error": "sampling already reported",
                      "code": "sampling_already_reported"
                    }
                  },
                  "number": {
                    "value": {
                      "error": "report number taken",
                      "code": "report_number_taken"
                    }
                  },
                  "lab": {
                    "value": {
                      "error": "lab not in force: suspended, or its accreditation expired before the signed date",
                      "code": "lab_not_in_force"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/trust": {
      "get": {
        "operationId": "getLotTrust",
        "summary": "Lot trust snapshot and history",
        "description": "The lot's persisted trust (L8, #33): the current snapshot (null before the lot's first recompute): the displayed tier (after the seal and the holds), the tier its evidence earns alone, the status (`on_hold` while a hold is open or escalated, an open public report's included: #46, kind `report`), the seal (the tier frozen when the lot left `open`, with its time; null before), the engine's machine explanation (reason codes with parameters and every journey step's tier, reasons and evidence sources: no prose) and when it was computed; whether the lot is queued for a recompute; its latest recorded holds; and one page of its history, newest first (a row per change of the snapshot, with the cause: the audit action of the mutation that queued it, `ingest`, or `migration`). Every evidence-changing write queues its lots and the request recomputes them right after its commit; the periodic job recomputes the rest. Times are Unix seconds. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of history.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "History page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's persisted trust.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotTrust"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "snapshot": {
                    "tier": "self_declared",
                    "computed": "self_declared",
                    "status": "normal",
                    "sealed": {
                      "tier": "self_declared",
                      "at": 1790560800.0,
                      "basis": "transition"
                    },
                    "explanation": {
                      "reasons": [
                        {
                          "code": "limited_by_step",
                          "params": {
                            "step": "harvest",
                            "tier": "self_declared"
                          }
                        },
                        {
                          "code": "limited_by_step",
                          "params": {
                            "step": "packing",
                            "tier": "self_declared"
                          }
                        }
                      ],
                      "steps": [
                        {
                          "step": "registration",
                          "tier": "cross_checked",
                          "reasons": [
                            {
                              "code": "lab_evidence_absent",
                              "params": {
                                "evidence": "authority_certificate"
                              }
                            }
                          ],
                          "sources": [
                            "signed_app",
                            "registry"
                          ]
                        },
                        {
                          "step": "harvest",
                          "tier": "self_declared",
                          "reasons": [
                            {
                              "code": "no_signed_evidence",
                              "params": {}
                            }
                          ],
                          "sources": [
                            "tenant_entry"
                          ]
                        },
                        {
                          "step": "measurement",
                          "tier": "cross_checked",
                          "reasons": [
                            {
                              "code": "lab_tier_not_applicable",
                              "params": {}
                            },
                            {
                              "code": "measurement_overrides_present",
                              "params": {
                                "count": 3
                              }
                            }
                          ],
                          "sources": [
                            "signed_device",
                            "scale",
                            "volume_quota"
                          ]
                        },
                        {
                          "step": "packing",
                          "tier": "self_declared",
                          "reasons": [
                            {
                              "code": "no_signed_evidence",
                              "params": {}
                            }
                          ],
                          "sources": [
                            "tenant_entry"
                          ]
                        }
                      ]
                    },
                    "computed_at": 1790560800.0
                  },
                  "queued": false,
                  "holds": [
                    {
                      "id": 4,
                      "kind": "quarantine",
                      "status": "resolved",
                      "opened_at": 1790474400.0,
                      "closed_at": 1790478000.0
                    }
                  ],
                  "history": [
                    {
                      "id": 12,
                      "tier": "self_declared",
                      "computed": "self_declared",
                      "status": "normal",
                      "sealed_tier": "self_declared",
                      "cause": "lot.seal",
                      "computed_at": 1790560800.0
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/close": {
      "post": {
        "operationId": "closeLot",
        "summary": "Close and digitally sign a lot (sealed manifest)",
        "description": "Closes a draft or open lot (its open or paused measurement sessions are closed and its closed_at set, as a lot close does) and signs the lot's manifest with the active issuer key of its facility (L9: did:web) as a VC-JOSE credential (see LotSeal), in one transaction that also takes the lot's trust seal (the tier frozen when the lot leaves open; already taken for a packed or shipped lot) and writes the audit row. A closed, packed or shipped lot is signed without a status change, so a lot signed after its departure carries its packing and shipping. The manifest is what was recorded at the seal time; afterwards a review of an envelope bound to one of its fruits changes the envelope's status only (alert lot_sealed). A lot is signed once. Refused with 409 when the confirmed fruit count differs from the lot's, a fruit is in review (`pending_review`), the lot is recalled or withdrawn or already sealed, the facility has no active issuer key, or the manifest would list more than 5,000 fruits or 20,000 envelopes; 503 without a key-encryption key. Audited (`lot.close`: the key id, the manifest hash and the counts; never the credential). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LotCloseRequest"
              },
              "example": {
                "confirm_counts": {
                  "fruits": 128
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The lot's seal.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotSeal"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "status": "shipped",
                  "sealed_at": 1790754000.0,
                  "sealed_by": "user-12",
                  "key_id": "did:web:txng.theio.vn:tanphu#key-1",
                  "manifest_sha256": "a869373f50f23727be3ef525863a48347c2c7d057119b62e02076adaa472d617",
                  "fruit_count": 128,
                  "event_count": 397,
                  "credential": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSNrZXktMSIsInR5cCI6InZjK2p3dCJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdDozZjljMmE3YmU0MWQ0YzBhOWU4YjZkNWYxYTJjM2I0ZCIsImxvdCI6eyJjb2RlIjoiTE8tMjYwOTI4LTAxNCJ9fSwiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdC1zZWFsOjNmOWMyYTdiZTQxZDRjMGE5ZThiNmQ1ZjFhMmMzYjRkIiwiaXNzdWVyIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSIsInR5cGUiOlsiVmVyaWZpYWJsZUNyZWRlbnRpYWwiLCJBZ3JpVHJhY2VMb3RTZWFsIl0sInZhbGlkRnJvbSI6IjIwMjYtMDktMzBUMDc6NDA6MDBaIn0.kctQ5XyOhXmF4wAaMoRTYUURRmG5IFU2VbzNcoaa483PwGtJks5WlZMAGrcxteF8ryX2IaBEaL_wgq8vWqCWIw"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body other than exactly confirm_counts.fruits, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: note",
                      "code": "unknown_field"
                    }
                  },
                  "confirm_counts": {
                    "value": {
                      "error": "confirm_counts.fruits must be a non-negative integer",
                      "code": "confirm_counts_fruits_must_be_a_non_negative_integer"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot cannot be signed: see the description. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "counts_changed": {
                    "value": {
                      "error": "counts changed: the lot has 128 fruits",
                      "code": "counts_changed"
                    }
                  },
                  "fruits_in_review": {
                    "value": {
                      "error": "fruits in review: 2",
                      "code": "fruits_in_review"
                    }
                  },
                  "already_sealed": {
                    "value": {
                      "error": "lot already sealed",
                      "code": "lot_already_sealed"
                    }
                  },
                  "invalid_transition": {
                    "value": {
                      "error": "invalid transition: recalled to sealed",
                      "code": "invalid_transition"
                    }
                  },
                  "no_active_issuer_key": {
                    "value": {
                      "error": "no active issuer key: facility VN-TGPH-021",
                      "code": "no_active_issuer_key"
                    }
                  },
                  "too_large": {
                    "value": {
                      "error": "lot too large to seal: more than 5000 fruits",
                      "code": "lot_too_large_to_seal"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK), or the issuer key store cannot be used; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                  "code": "issuer_keys_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/lots/{lot}/manifest": {
      "get": {
        "operationId": "getLotManifest",
        "summary": "A lot's signed seal",
        "description": "The lot's seal (L10, #35): the signed credential of its manifest, its hash, the signing key and the counts (see LotSeal); 404 while the lot is not sealed. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's seal.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotSeal"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "status": "shipped",
                  "sealed_at": 1790754000.0,
                  "sealed_by": "user-12",
                  "key_id": "did:web:txng.theio.vn:tanphu#key-1",
                  "manifest_sha256": "a869373f50f23727be3ef525863a48347c2c7d057119b62e02076adaa472d617",
                  "fruit_count": 128,
                  "event_count": 397,
                  "credential": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSNrZXktMSIsInR5cCI6InZjK2p3dCJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdDozZjljMmE3YmU0MWQ0YzBhOWU4YjZkNWYxYTJjM2I0ZCIsImxvdCI6eyJjb2RlIjoiTE8tMjYwOTI4LTAxNCJ9fSwiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdC1zZWFsOjNmOWMyYTdiZTQxZDRjMGE5ZThiNmQ1ZjFhMmMzYjRkIiwiaXNzdWVyIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSIsInR5cGUiOlsiVmVyaWZpYWJsZUNyZWRlbnRpYWwiLCJBZ3JpVHJhY2VMb3RTZWFsIl0sInZhbGlkRnJvbSI6IjIwMjYtMDktMzBUMDc6NDA6MDBaIn0.kctQ5XyOhXmF4wAaMoRTYUURRmG5IFU2VbzNcoaa483PwGtJks5WlZMAGrcxteF8ryX2IaBEaL_wgq8vWqCWIw"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant (a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one), or the lot is not sealed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_found": {
                    "value": {
                      "error": "not found: LO-260928-014",
                      "code": "not_found"
                    }
                  },
                  "not_sealed": {
                    "value": {
                      "error": "lot not sealed",
                      "code": "lot_not_sealed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/facilities/{code}/issuer-keys": {
      "get": {
        "operationId": "listIssuerKeys",
        "summary": "List a facility's issuer keys",
        "description": "Every did:web issuer key of the facility (#34), active, retired and revoked, by number; never a private key. Read like the facility: admins and auditors tenant-wide, an operator only within its facilities. Not audited (a read).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "facility_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          }
        ],
        "responses": {
          "200": {
            "description": "The facility's keys.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IssuerKeyList"
                },
                "example": {
                  "items": [
                    {
                      "facility": "VN-TGPH-021",
                      "n": 1,
                      "name": "key-1",
                      "did": "did:web:txng.theio.vn:tanphu",
                      "key_id": "did:web:txng.theio.vn:tanphu#key-1",
                      "alg": "ES256",
                      "public_jwk": {
                        "kty": "EC",
                        "crv": "P-256",
                        "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
                        "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
                      },
                      "status": "active",
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5,
                      "retired_at": null,
                      "revoked_at": null,
                      "revoke_reason": null,
                      "revoked_by": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this tenant: a facility of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createIssuerKey",
        "summary": "Generate (rotate) a facility's issuer key",
        "description": "Generates the facility's next ES256 (P-256) key pair server-side as `key-<n>` and makes it the active key; a key active until now becomes `retired` and stays in the DID document, so what it signed stays verifiable (a rotation). The request has no body (or `{}`). The private key is encrypted under AGRITRACE_ISSUER_KEK into its own 0600 file and is never returned, logged or audited. The facility must be approved; its slug (the DID path) is frozen from then on. Audited (`issuer_key.create`, entity `<facility>#key-<n>`). Allowed for tenant_admin and platform_admin of the owning tenant. Second admin approval (INTEGRITY-3, #203): while the company requires a second admin (PUT /v1/company/four-eyes), a direct call answers 403 `second_admin_approval_required` before anything is done (no audit row, no Idempotency-Key used): ask for it with POST /v1/approval-requests, and another admin of the company approves it.",
        "x-sdk-description": "Generates the facility's next ES256 (P-256) key pair server-side as `key-<n>` and makes it the active key; a key active until now becomes `retired` and stays in the DID document, so what it signed stays verifiable (a rotation). The request has no body (or `{}`). The private key is encrypted under AGRITRACE_ISSUER_KEK into its own 0600 file and is never returned, logged or audited. The facility must be approved; its slug (the DID path) is frozen from then on. Audited (`issuer_key.create`, entity `<facility>#key-<n>`). Allowed for tenant_admin and platform_admin of the owning tenant.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "issuer_key_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "201": {
            "description": "The new active key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IssuerKey"
                },
                "example": {
                  "facility": "VN-TGPH-021",
                  "n": 1,
                  "name": "key-1",
                  "did": "did:web:txng.theio.vn:tanphu",
                  "key_id": "did:web:txng.theio.vn:tanphu#key-1",
                  "alg": "ES256",
                  "public_jwk": {
                    "kty": "EC",
                    "crv": "P-256",
                    "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
                    "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
                  },
                  "status": "active",
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "retired_at": null,
                  "revoked_at": null,
                  "revoke_reason": null,
                  "revoked_by": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body with any field, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: an issuer key is generated by the server and takes no input",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this tenant: a facility of another tenant, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGPH-021",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The facility is not approved, or it already holds 100 keys. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "issuer key limit reached",
                      "code": "issuer_key_limit_reached"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK), or the store cannot be used; nothing changed. Retry after `Retry-After` seconds once it is configured.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                  "code": "issuer_keys_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/facilities/{code}/issuer-keys/{key}/revoke": {
      "post": {
        "operationId": "revokeIssuerKey",
        "summary": "Revoke a compromised issuer key",
        "description": "Marks the key `revoked` (reason `compromise`, the only one: a rotation generates a new key instead). It leaves the DID document at once, so nothing it signed verifies any more, and one high-severity `issuer_key_compromised` alert is raised for the tenant. A revoked active key leaves the facility without an active key until a new one is generated. Audited (`issuer_key.revoke`). Allowed for tenant_admin and platform_admin of the owning tenant. Step-up (#87): a signed-in session of an account with two-step sign-in must have confirmed a code from its authenticator app (or a backup code) within the last 5 minutes and its password within the last 10 minutes, else 401 `mfa_step_up_required` before anything is done (no audit row): confirm both with POST /v1/auth/reauth, then repeat the request. A session of an account without two-step sign-in, API tokens and API clients are served as before.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "issuer_key_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Facility code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGPH-021"
          },
          {
            "name": "key",
            "in": "path",
            "required": true,
            "description": "Key name `key-<n>`.",
            "schema": {
              "type": "string"
            },
            "example": "key-1"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/IssuerKeyRevoke"
              },
              "example": {
                "reason": "compromise"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The key after revocation.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IssuerKey"
                },
                "example": {
                  "facility": "VN-TGPH-021",
                  "n": 1,
                  "name": "key-1",
                  "did": "did:web:txng.theio.vn:tanphu",
                  "key_id": "did:web:txng.theio.vn:tanphu#key-1",
                  "alg": "ES256",
                  "public_jwk": {
                    "kty": "EC",
                    "crv": "P-256",
                    "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
                    "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
                  },
                  "status": "revoked",
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "retired_at": null,
                  "revoked_at": 1790086400.5,
                  "revoke_reason": "compromise",
                  "revoked_by": "admin@coop.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a reason other than compromise, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: compromise (a rotation generates a new key instead)",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            },
            "x-sdk-description": "No valid session, API token or legacy token."
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such facility for this tenant (another tenant's, or outside an operator's facilities, answers like a missing one), or no such key of the facility.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: key-9",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The key is already revoked. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_already_revoked": {
                    "value": {
                      "error": "key already revoked",
                      "code": "key_already_revoked"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Marks the key `revoked` (reason `compromise`, the only one: a rotation generates a new key instead). It leaves the DID document at once, so nothing it signed verifies any more, and one high-severity `issuer_key_compromised` alert is raised for the tenant. A revoked active key leaves the facility without an active key until a new one is generated. Audited (`issuer_key.revoke`). Allowed for tenant_admin and platform_admin of the owning tenant."
      }
    },
    "/{slug}/did.json": {
      "get": {
        "operationId": "getDidDocument",
        "summary": "A facility's did:web DID document",
        "description": "The did:web resolution URL of `did:web:<AGRITRACE_DID_DOMAIN>:<slug>` (#34): served at the root of the issuer host, so the edge proxy routes `/<slug>/did.json` to the backend. Anonymous and tenant-less (credentials change nothing), rate limited with the /v1/public/* bucket. Lists the facility's active and retired keys (a rotation keeps old credentials verifiable), never a revoked one. Not audited (a read).",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "slug",
            "in": "path",
            "required": true,
            "description": "The facility's slug.",
            "schema": {
              "type": "string"
            },
            "example": "tanphu"
          }
        ],
        "responses": {
          "200": {
            "description": "The DID document.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate): a rotation or revocation is seen within a minute (at most six, the first request after a quiet period).",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`: browser-based resolvers may read the document.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/did+json": {
                "schema": {
                  "$ref": "#/components/schemas/DidDocument"
                },
                "example": {
                  "@context": [
                    "https://www.w3.org/ns/did/v1",
                    "https://w3id.org/security/suites/jws-2020/v1"
                  ],
                  "id": "did:web:txng.theio.vn:tanphu",
                  "verificationMethod": [
                    {
                      "id": "did:web:txng.theio.vn:tanphu#key-1",
                      "type": "JsonWebKey2020",
                      "controller": "did:web:txng.theio.vn:tanphu",
                      "publicKeyJwk": {
                        "kty": "EC",
                        "crv": "P-256",
                        "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
                        "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
                      }
                    }
                  ],
                  "assertionMethod": [
                    "did:web:txng.theio.vn:tanphu#key-1"
                  ]
                }
              }
            }
          },
          "404": {
            "description": "No facility has this slug, or it lists no key (none generated, or every key revoked). Every such slug gets this same body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale): a rotation or revocation is seen within a minute.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`: browser-based resolvers may read the document.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: did document",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* and did.json requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/labs/{code}/did.json": {
      "get": {
        "operationId": "getLabDidDocument",
        "summary": "A lab's did:web DID document",
        "description": "#142: the did:web resolution URL of `did:web:<AGRITRACE_DID_DOMAIN>:labs:<code>`, a lab's DID: served at the root of the issuer host, so the edge proxy routes `/labs/<code>/did.json` to the backend. Anonymous and tenant-less (credentials change nothing), rate limited with the /v1/public/* bucket. Lists the lab's keys as JsonWebKey2020 verification methods `<did>#<kid>`, each also an assertion method: the active ones and those revoked for a rotation (what they signed stays verifiable), never one revoked for compromise, at most 100, the newest. The lab's conformity credentials (GET /v1/public/lots/{publicId}/lab-credential) verify with the key their `kid` names. Not audited (a read). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "The lab's code (`LAB-<country>-<id>`). Any other value is 404 like an unknown code.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          }
        ],
        "responses": {
          "200": {
            "description": "The DID document.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate): a rotation or revocation is seen within a minute (at most six, the first request after a quiet period).",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`: browser-based resolvers may read the document.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/did+json": {
                "schema": {
                  "$ref": "#/components/schemas/DidDocument"
                },
                "example": {
                  "@context": [
                    "https://www.w3.org/ns/did/v1",
                    "https://w3id.org/security/suites/jws-2020/v1"
                  ],
                  "id": "did:web:txng.theio.vn:labs:LAB-VN-118",
                  "verificationMethod": [
                    {
                      "id": "did:web:txng.theio.vn:labs:LAB-VN-118#LAB-VN-118.k1",
                      "type": "JsonWebKey2020",
                      "controller": "did:web:txng.theio.vn:labs:LAB-VN-118",
                      "publicKeyJwk": {
                        "kty": "EC",
                        "crv": "P-256",
                        "x": "1OihyfaVy4QEeRRKoAtNhYPW8jD1Z-qTeH4bQcQMupk",
                        "y": "XgO6W85O0u11FOOKfyoihvZGt3V95MVuNe5_oJ0IUqU"
                      }
                    },
                    {
                      "id": "did:web:txng.theio.vn:labs:LAB-VN-118#LAB-VN-118.portal",
                      "type": "JsonWebKey2020",
                      "controller": "did:web:txng.theio.vn:labs:LAB-VN-118",
                      "publicKeyJwk": {
                        "kty": "EC",
                        "crv": "P-256",
                        "x": "VtKPC0MKX0r3i6575aZXWDmtaO5A1MkbEt6pZbNzyCM",
                        "y": "2B7hEkDmeriEqAMs1nhNd6FfnwwnLa-y0j1yItMaQQA"
                      }
                    }
                  ],
                  "assertionMethod": [
                    "did:web:txng.theio.vn:labs:LAB-VN-118#LAB-VN-118.k1",
                    "did:web:txng.theio.vn:labs:LAB-VN-118#LAB-VN-118.portal"
                  ]
                }
              }
            }
          },
          "404": {
            "description": "No lab has this code, or it lists no key (none registered, or every key revoked for compromise). Every such code gets this same body, the facility document's.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale): a rotation or revocation is seen within a minute.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`: browser-based resolvers may read the document.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: did document",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* and did.json requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/public/fruits/{publicId}/credential": {
      "get": {
        "operationId": "getPublicFruitCredential",
        "summary": "Public UNTP credential of a fruit",
        "description": "X3 (#44): the fruit's UNTP Digital Product Passport (granularity `item`), issued with its lot's credential when the lot was sealed, in the same form (compact JWS, ES256, `typ` `vc+jwt`): UNTP 0.7.0 for a lot sealed since #162 (the product identified by `https://<domain>/q/<publicId>`), UNTP 0.6.1 for a lot sealed before, served as stored. Offered under exactly the public fruit record's visibility. A download named `untp-dpp-<fruit public id>.jwt`. Withdrawn (404) once the key is revoked. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the visibility lookups of the public record, then one statement that returns the text stored when the lot was sealed; nothing is decoded, verified or signed per request. Cross-origin readable (`Access-Control-Allow-Origin: *`), like the DID document, so a verifier's page can fetch it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The fruit's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "73879f17d0930440809333f141385eb6"
          }
        ],
        "responses": {
          "200": {
            "description": "The stored compact JWS.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"untp-dpp-<fruit public id>.jwt\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/vc+jwt": {
                "schema": {
                  "$ref": "#/components/schemas/PublicCredential"
                },
                "example": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnZuLXRncGgtMDIxI2tleS0xIiwidHlwIjoidmMrand0In0.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiLCJodHRwczovL3ZvY2FidWxhcnkudW5jZWZhY3Qub3JnL3VudHAvMC43LjAvY29udGV4dC8iXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiYmF0Y2hOdW1iZXIiOiJMTy0yNjA5MjgtMDE0IiwiY2hhcmFjdGVyaXN0aWNzIjp7ImRldmljZSI6eyJtb2RlbCI6IlNGLTEwMCIsInNlcmlhbCI6IjA0MTcifSwiZWF0aW5nV2luZG93Ijp7ImVuZCI6IjIwMjYtMTAtMDIiLCJzdGFydCI6IjIwMjYtMTAtMDEifSwiZ3JhZGUiOiJBIiwiZ3Jvd2luZ0FyZWEiOnsiY29kZSI6IlZOLVRHT1ItMDM4NyIsImxvY2FsaXR5IjoiTmfFqSBIaeG7h3AsIENhaSBM4bqteSwgVGnhu4FuIEdpYW5nIn0sImxvdCI6InVybjphZ3JpdHJhY2U6bG90OkxPLTI2MDkyOC0wMTQiLCJtZWFzdXJlZEF0IjoiMjAyNi0wOS0yOFQwMTo1NjowMFoiLCJtZWFzdXJlbWVudEV2ZW50IjoidXJuOnV1aWQ6ZDdlN2ZiODUtOWYwYy00NGViLTliOWQtNjMwMDA4YzZiM2FhIiwibW9kZWxDb25maWRlbmNlIjowLjkxLCJyaXBlbmVzc0xldmVsIjozLCJzZW5zb3J5T3ZlcnJpZGUiOmZhbHNlLCJ0eXBlIjpbIkNoYXJhY3RlcmlzdGljcyJdLCJ2YXJpZXR5IjoiUmk2In0sImNvdW50cnlPZlByb2R1Y3Rpb24iOnsiY291bnRyeUNvZGUiOiJWTiIsImNvdW50cnlOYW1lIjoiVmlldCBOYW0ifSwiZGltZW5zaW9ucyI6eyJ3ZWlnaHQiOnsidW5pdCI6IktHTSIsInZhbHVlIjoyLjg0fX0sImlkIjoiaHR0cHM6Ly90eG5nLnRoZWlvLnZuL3EvMDJhYmRlNDI0ZjBiYjU1ZGY0ZmM3MTg3NjY1NzhmNGYiLCJpZEdyYW51bGFyaXR5IjoiaXRlbSIsImlkU2NoZW1lIjp7ImlkIjoiaHR0cHM6Ly90eG5nLnRoZWlvLnZuIiwibmFtZSI6IkNyb3BQYXRoIHB1YmxpYyByZWNvcmRzIiwidHlwZSI6WyJJZGVudGlmaWVyU2NoZW1lIl19LCJpdGVtTnVtYmVyIjoiUS0wMDEtMDAwMSIsIm5hbWUiOiJEdXJpYW4gUmk2IiwicHJvZHVjZWRBdEZhY2lsaXR5Ijp7ImlkIjoidXJuOmFncml0cmFjZTpsb2M6Vk4tVEdQSC0wMjEiLCJpZFNjaGVtZSI6eyJpZCI6InVybjphZ3JpdHJhY2U6bG9jIiwibmFtZSI6IkNyb3BQYXRoIGZhY2lsaXR5IGNvZGVzIiwidHlwZSI6WyJJZGVudGlmaWVyU2NoZW1lIl19LCJuYW1lIjoiVMOibiBQaMO6IiwicmVnaXN0ZXJlZElkIjoiVk4tVEdQSC0wMjEiLCJ0eXBlIjpbIkZhY2lsaXR5Il19LCJwcm9kdWN0Q2F0ZWdvcnkiOlt7ImNvZGUiOiIwMTMxOSIsIm5hbWUiOiJPdGhlciB0cm9waWNhbCBhbmQgc3VidHJvcGljYWwgZnJ1aXRzLCBuLmUuYy4iLCJzY2hlbWVJZCI6Imh0dHBzOi8vdW5zdGF0cy51bi5vcmcvdW5zZC9jbGFzc2lmaWNhdGlvbnMvRWNvbi9jcGMvIiwic2NoZW1lTmFtZSI6IlVOIENlbnRyYWwgUHJvZHVjdCBDbGFzc2lmaWNhdGlvbiAoQ1BDKSJ9XSwicHJvZHVjdGlvbkRhdGUiOiIyMDI2LTA5LTI3IiwicmVsYXRlZERvY3VtZW50IjpbeyJsaW5rTmFtZSI6IlB1YmxpYyBmcnVpdCByZWNvcmQiLCJsaW5rVHlwZSI6Imh0dHBzOi8vZ3MxLm9yZy92b2MvcGlwIiwibGlua1VSTCI6Imh0dHBzOi8vdHhuZy50aGVpby52bi92aS9xLzAyYWJkZTQyNGYwYmI1NWRmNGZjNzE4NzY2NTc4ZjRmIiwibWVkaWFUeXBlIjoidGV4dC9odG1sIn0seyJkaWdlc3RNdWx0aWJhc2UiOiJ1RWlBeFRHbDUzRGdPV2hDSjREMzI0aDhKN2pla2NwR3gtN2RMT1lnTjdYeFg4dyIsImxpbmtOYW1lIjoiVU5UUCBwYXNzcG9ydCBvZiB0aGUgbG90IiwibGlua1R5cGUiOiJodHRwczovL3Rlc3QudW5jZWZhY3Qub3JnL3ZvY2FidWxhcnkvbGlua1R5cGVzL2RwcCIsImxpbmtVUkwiOiJodHRwczovL3R4bmcudGhlaW8udm4vdjEvcHVibGljL2xvdHMvZDgwNmFhNmQ5NjYzODVmZjlhNGZmNzhkNTM3MTQzNTYvY3JlZGVudGlhbCIsIm1lZGlhVHlwZSI6ImFwcGxpY2F0aW9uL3ZjK2p3dCJ9LHsiZGlnZXN0TXVsdGliYXNlIjoidUVpQU9yUTZNWWwydmFrc0tWRjVaSG9TeEJueWdIVkNvZHl5Z25xMEVsWDMzQ0EiLCJsaW5rTmFtZSI6IkVQQ0lTIDIuMCBldmVudHMgb2YgdGhlIGxvdCIsImxpbmtUeXBlIjoiaHR0cHM6Ly9nczEub3JnL3ZvYy90cmFjZWFiaWxpdHkiLCJsaW5rVVJMIjoiaHR0cHM6Ly90eG5nLnRoZWlvLnZuL3YxL3B1YmxpYy9sb3RzL2Q4MDZhYTZkOTY2Mzg1ZmY5YTRmZjc4ZDUzNzE0MzU2L2VwY2lzLmpzb25sZCIsIm1lZGlhVHlwZSI6ImFwcGxpY2F0aW9uL2xkK2pzb24ifV0sInR5cGUiOlsiUHJvZHVjdCJdfSwiaWQiOiJ1cm46YWdyaXRyYWNlOmZydWl0LXBhc3Nwb3J0OjAyYWJkZTQyNGYwYmI1NWRmNGZjNzE4NzY2NTc4ZjRmIiwiaXNzdWVyIjp7ImlkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnZuLXRncGgtMDIxIiwibmFtZSI6IlTDom4gUGjDuiIsInR5cGUiOlsiQ3JlZGVudGlhbElzc3VlciJdfSwibmFtZSI6IkRpZ2l0YWwgUHJvZHVjdCBQYXNzcG9ydCBvZiBmcnVpdCBRLTAwMS0wMDAxIiwidHlwZSI6WyJEaWdpdGFsUHJvZHVjdFBhc3Nwb3J0IiwiVmVyaWZpYWJsZUNyZWRlbnRpYWwiXSwidmFsaWRGcm9tIjoiMjAyNi0wOS0yOVQwODo0MTowMFoifQ.-8U2QZqem3_mIhPsp3C47MXAJCTPp-blmIzX7_Fxsoh1SC5JTeq1-fxdGbuIFK_rA2VlDOo2RYSezKOfjCHmEQ",
                "x-sdk-example": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSNrZXktMSIsInR5cCI6InZjK2p3dCJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiLCJodHRwczovL3Rlc3QudW5jZWZhY3Qub3JnL3ZvY2FidWxhcnkvdW50cC9kcHAvMC42LjEvIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImdyYW51bGFyaXR5TGV2ZWwiOiJiYXRjaCIsImlkIjoidXJuOmFncml0cmFjZTpsb3Q6MDc0ZWIwOWIzNzFmYzcxYzM4MGRhMjM1YWVhOWMxNGEiLCJwcm9kdWN0Ijp7ImJhdGNoTnVtYmVyIjoiTE8tMjYwOTI4LTAxNCIsImNoYXJhY3RlcmlzdGljcyI6eyJmcnVpdENvdW50IjoxMjMsImdyb3dpbmdBcmVhIjp7ImNvZGUiOiJWTi1UR09SLTAzODciLCJsb2NhbGl0eSI6Ik5nxakgSGnhu4dwLCBDYWkgTOG6rXksIFRp4buBbiBHaWFuZyJ9LCJuZXRNYXNzIjp7InR5cGUiOlsiTWVhc3VyZSJdLCJ1bml0IjoiS0dNIiwidmFsdWUiOjM0OS42fSwidHlwZSI6WyJDaGFyYWN0ZXJpc3RpY3MiXSwidmFyaWV0eSI6IlJpNiJ9LCJjb3VudHJ5T2ZQcm9kdWN0aW9uIjoiVk4iLCJmdXJ0aGVySW5mb3JtYXRpb24iOlt7ImxpbmtOYW1lIjoiUHVibGljIGxvdCByZWNvcmQiLCJsaW5rVHlwZSI6InRleHQvaHRtbCIsImxpbmtVUkwiOiJodHRwczovL3R4bmcudGhlaW8udm4vdmkvbC8wNzRlYjA5YjM3MWZjNzFjMzgwZGEyMzVhZWE5YzE0YSIsInR5cGUiOlsiTGluayJdfV0sImlkIjoidXJuOmFncml0cmFjZTpsb3Q6TE8tMjYwOTI4LTAxNCIsIm5hbWUiOiJEdXJpYW4gUmk2IiwicHJvZHVjZWRBdEZhY2lsaXR5Ijp7ImlkIjoidXJuOmFncml0cmFjZTpsb2M6Vk4tVEdQSC0wMjEiLCJuYW1lIjoiVMOibiBQaMO6In0sInByb2R1Y3Rpb25EYXRlIjoiMjAyNi0wOS0yNyIsInR5cGUiOlsiUHJvZHVjdCJdfSwidHJhY2VhYmlsaXR5SW5mb3JtYXRpb24iOlt7InRyYWNlYWJpbGl0eUV2ZW50IjpbeyJlbmNyeXB0aW9uTWV0aG9kIjoibm9uZSIsImhhc2hEaWdlc3QiOiI0YWVlNTIxYzRhOTEyODE0MzA2Y2U2MWJiNGFiMjk0MzEyMTRmZTk4MTMzZDRmMDY1MzU2NWZhZTM3OGZhMTAwIiwiaGFzaE1ldGhvZCI6IlNIQS0yNTYiLCJsaW5rTmFtZSI6IkVQQ0lTIDIuMCBldmVudHMgb2YgdGhlIGxvdCIsImxpbmtUeXBlIjoiYXBwbGljYXRpb24vbGQranNvbiIsImxpbmtVUkwiOiJodHRwczovL3R4bmcudGhlaW8udm4vdjEvcHVibGljL2xvdHMvMDc0ZWIwOWIzNzFmYzcxYzM4MGRhMjM1YWVhOWMxNGEvZXBjaXMuanNvbmxkIiwidHlwZSI6WyJTZWN1cmVMaW5rIiwiTGluayJdfV0sInR5cGUiOlsiVHJhY2VhYmlsaXR5UGVyZm9ybWFuY2UiXSwidmFsdWVDaGFpblByb2Nlc3MiOiJoYXJ2ZXN0LCBtZWFzdXJlbWVudCwgcGFja2luZyBhbmQgc2hpcHBpbmcgb2YgdGhlIGxvdCJ9XSwidHlwZSI6WyJQcm9kdWN0UGFzc3BvcnQiXX0sImlkIjoidXJuOmFncml0cmFjZTpsb3QtcGFzc3BvcnQ6MDc0ZWIwOWIzNzFmYzcxYzM4MGRhMjM1YWVhOWMxNGEiLCJpc3N1ZXIiOnsiaWQiOiJkaWQ6d2ViOnR4bmcudGhlaW8udm46dGFucGh1IiwibmFtZSI6IlTDom4gUGjDuiIsInR5cGUiOlsiQ3JlZGVudGlhbElzc3VlciJdfSwidHlwZSI6WyJEaWdpdGFsUHJvZHVjdFBhc3Nwb3J0IiwiVmVyaWZpYWJsZUNyZWRlbnRpYWwiXSwidmFsaWRGcm9tIjoiMjAyNi0wOS0zMFQwNzo0MDowMFoifQ.gip_kxOtNSvzPm4BapjXtFRkbxM2Ajb8giNAczwJsAgS81bIola3xhMbkIU-Z8ucIfXLtWk-bnROtqLFk-IcMw"
              }
            }
          },
          "404": {
            "description": "No credential: every id the public fruit route answers 404 for, a public fruit whose lot was not sealed with public documents or that was not published at the seal, and one whose issuer key was revoked. Every such id gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: fruits",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "X3 (#44): the fruit's UNTP Digital Product Passport (granularity `item`), issued with its lot's credential when the lot was sealed, in the same form (compact JWS, ES256, `typ` `vc+jwt`). Offered under exactly the public fruit record's visibility. A download named `untp-dpp-<fruit public id>.jwt`. Withdrawn (404) once the key is revoked. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the visibility lookups of the public record, then one statement that returns the text stored when the lot was sealed; nothing is decoded, verified or signed per request. Cross-origin readable (`Access-Control-Allow-Origin: *`), like the DID document, so a verifier's page can fetch it."
      }
    },
    "/v1/public/lots/{publicId}/epcis.jsonld": {
      "get": {
        "operationId": "getPublicLotEpcis",
        "summary": "Public EPCIS 2.0 document of a sealed lot",
        "description": "X3 (#44): the lot's EPCIS 2.0 JSON-LD document (GS1), issued once when the lot was sealed (L10, #35) and never changed: its accepted events, oldest first, minimised for the public (no operator, producer, parcel, attachment, coordinates, device signature or device id; the read point is the facility or the growing area). The lot's UNTP credential cites these exact bytes by SHA-256. A download named `epcis-<lot code>.jsonld`. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work and size: a document is at most 16 MiB (a lot whose document would be larger gets no public documents); after the visibility lookups of the public record, one statement reads the document's SHA-256 and size; an `If-None-Match` naming its ETag (the SHA-256) answers 304 without reading the text; otherwise the client's download bucket takes one token per started KiB (bursts of 32 MiB, then 64 KiB a second), then one statement returns the text stored when the lot was sealed; nothing is decoded, verified or signed per request. Cross-origin readable (`Access-Control-Allow-Origin: *`), like the DID document, so a verifier's page can fetch it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          },
          {
            "name": "If-None-Match",
            "in": "header",
            "required": false,
            "description": "An ETag of the document (its `ETag`: the SHA-256 of its bytes, quoted), a list of them or `*`; compared weakly (RFC 9110). When it names the document's tag the answer is 304.",
            "schema": {
              "type": "string"
            },
            "example": "\"9f2c0d5ab1e7c3f4a6b8d0e2f4a6c8e0b2d4f6a8c0e2a4c6e8a0c2e4a6c8e0b2\""
          }
        ],
        "responses": {
          "200": {
            "description": "The stored document, byte for byte (canonical JSON: sorted keys, compact).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate), with the strong ETag (its SHA-256). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The SHA-256 hex of the document's bytes, quoted (a strong ETag); the lot credential cites the same digest.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"epcis-<lot code>.jsonld\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/ld+json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicEpcisDocument"
                },
                "example": {
                  "@context": [
                    "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld",
                    {
                      "agri": "https://agritrace.vn/epcis/"
                    }
                  ],
                  "type": "EPCISDocument",
                  "schemaVersion": "2.0",
                  "creationDate": "2026-09-30T07:40:00Z",
                  "epcisBody": {
                    "eventList": [
                      {
                        "type": "ObjectEvent",
                        "eventID": "urn:uuid:0b1f7c9e-2a51-4c8e-9d7a-3f0e8c6b1a42",
                        "eventTime": "2026-09-28T08:56:00.000+07:00",
                        "eventTimeZoneOffset": "+07:00",
                        "action": "OBSERVE",
                        "bizStep": "inspecting",
                        "epcList": [],
                        "quantityList": [
                          {
                            "epcClass": "urn:agritrace:lot:LO-260928-014"
                          }
                        ],
                        "readPoint": {
                          "id": "urn:agritrace:loc:VN-TGPH-021"
                        },
                        "bizLocation": {
                          "id": "urn:agritrace:loc:VN-TGPH-021"
                        },
                        "sensorElementList": [
                          {
                            "sensorMetadata": {
                              "time": "2026-09-28T08:56:00.000+07:00",
                              "deviceMetadata": "agri:profile/vn.agritrace.durian-knocker@1.0.0"
                            },
                            "sensorReport": [
                              {
                                "type": "https://agritrace.vn/voc/RipenessLevel",
                                "value": 3,
                                "uom": "C62"
                              }
                            ]
                          }
                        ],
                        "agri:fruit": "Q-014-0001",
                        "agri:seq": 12
                      }
                    ]
                  }
                }
              }
            }
          },
          "304": {
            "description": "Not modified: the request's `If-None-Match` names the document's ETag. No body; the text is not read and the download bucket is not charged.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate), with the strong ETag.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The document's ETag, as on the 200.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "No document: every id the public lot route answers 404 for, and a public lot that was not sealed with public documents. Every such id gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds. Also when this client's EPCIS download bucket (one token per started KiB of the document: bursts of 32 MiB, then 64 KiB a second) does not hold the document's size; that bucket is taken after the visibility lookups and before the text is read, and a 304 never takes from it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/lots/{publicId}/credential": {
      "get": {
        "operationId": "getPublicLotCredential",
        "summary": "Public UNTP credential of a sealed lot",
        "description": "X3 (#44): the lot's UNTP Digital Product Passport as a VC 2.0 credential secured with VC-JOSE (W3C Recommendation 2025-05-15): a compact JWS (ES256, `typ` `vc+jwt`, `kid` the issuer key's DID URL), issued and verified once when the lot was sealed, with the facility's issuer key named by the public lot record's `issuer`. #162: a lot sealed since the upgrade gets a UNTP 0.7.0 passport (`@context` https://vocabulary.uncefact.org/untp/0.7.0/context/; its subject is the product, identified by the URL of its public record `https://<domain>/l/<publicId>`, whose link set GET /v1/public/linkset answers); a lot sealed before keeps the UNTP 0.6.1 passport it was sealed with, byte for byte. It verifies with that key in the facility's `/{slug}/did.json` (/developers/downloads/verify.md). A download named `untp-dpp-<lot code>.jwt`. Its lab conformity claims are made only from a report the public lab step accepts (ADR 0001: its key not revoked for compromise, from the lab the sampling assigned). Withdrawn (404) once that key is revoked for compromise, or once the lab key its claims cite is. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the visibility lookups of the public record, then one statement that returns the text stored when the lot was sealed; nothing is decoded, verified or signed per request. Cross-origin readable (`Access-Control-Allow-Origin: *`), like the DID document, so a verifier's page can fetch it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          }
        ],
        "responses": {
          "200": {
            "description": "The stored compact JWS.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"untp-dpp-<lot code>.jwt\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/vc+jwt": {
                "schema": {
                  "$ref": "#/components/schemas/PublicCredential"
                },
                "example": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnZuLXRncGgtMDIxI2tleS0xIiwidHlwIjoidmMrand0In0.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiLCJodHRwczovL3ZvY2FidWxhcnkudW5jZWZhY3Qub3JnL3VudHAvMC43LjAvY29udGV4dC8iXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiYmF0Y2hOdW1iZXIiOiJMTy0yNjA5MjgtMDE0IiwiY2hhcmFjdGVyaXN0aWNzIjp7ImVwY0NsYXNzIjoidXJuOmFncml0cmFjZTpsb3Q6TE8tMjYwOTI4LTAxNCIsImZydWl0Q291bnQiOjUsImdyb3dpbmdBcmVhIjp7ImNvZGUiOiJWTi1UR09SLTAzODciLCJsb2NhbGl0eSI6Ik5nxakgSGnhu4dwLCBDYWkgTOG6rXksIFRp4buBbiBHaWFuZyJ9LCJ0eXBlIjpbIkNoYXJhY3RlcmlzdGljcyJdLCJ2YXJpZXR5IjoiUmk2In0sImNvdW50cnlPZlByb2R1Y3Rpb24iOnsiY291bnRyeUNvZGUiOiJWTiIsImNvdW50cnlOYW1lIjoiVmlldCBOYW0ifSwiZGltZW5zaW9ucyI6eyJ3ZWlnaHQiOnsidW5pdCI6IktHTSIsInZhbHVlIjoxNC40MX19LCJpZCI6Imh0dHBzOi8vdHhuZy50aGVpby52bi9sL2Q4MDZhYTZkOTY2Mzg1ZmY5YTRmZjc4ZDUzNzE0MzU2IiwiaWRHcmFudWxhcml0eSI6ImJhdGNoIiwiaWRTY2hlbWUiOnsiaWQiOiJodHRwczovL3R4bmcudGhlaW8udm4iLCJuYW1lIjoiQ3JvcFBhdGggcHVibGljIHJlY29yZHMiLCJ0eXBlIjpbIklkZW50aWZpZXJTY2hlbWUiXX0sIm5hbWUiOiJEdXJpYW4gUmk2IiwicGVyZm9ybWFuY2VDbGFpbSI6W3siY2xhaW1EYXRlIjoiMjAyNi0wOS0yOSIsImNsYWltZWRQZXJmb3JtYW5jZSI6W3sic2NvcmUiOnsiY29kZSI6InBhc3MiLCJkZWZpbml0aW9uIjoiZXZlcnkgc2FtcGxlIHdpdGhpbiB0aGUgQ04gbWFya2V0J3MgbGltaXQifX1dLCJjb25mb3JtaXR5VG9waWMiOlt7ImlkIjoiaHR0cHM6Ly92b2NhYnVsYXJ5LnVuY2VmYWN0Lm9yZy9jb25mb3JtaXR5LXRvcGljcy9zYW5pdGFyeS1hbmQtcGh5dG9zYW5pdGFyeSIsIm5hbWUiOiJTYW5pdGFyeSBhbmQgUGh5dG9zYW5pdGFyeSBNZWFzdXJlcyIsInR5cGUiOlsiQ29uZm9ybWl0eVRvcGljIl19XSwiZGVzY3JpcHRpb24iOiJhdXJhbWluZV9vOiAxIHNhbXBsZXMsIGRldGVjdGVkIGluIDA7IGxpbWl0OiBBdXJhbWluZSBPIGlzIGEgbm9uLWVkaWJsZSBzdWJzdGFuY2UgaW4gQ2hpbmEgKE1pbmlzdHJ5IG9mIEhlYWx0aCBsaXN0LCAyMDA4KTogbm8gbGV2ZWwgaXMgcGVybWl0dGVkOyBHQUNDIHJlcXVpcmVzIGFuIGF1cmFtaW5lIE8gdGVzdCByZXBvcnQgd2l0aCBldmVyeSBkdXJpYW4gc2hpcG1lbnQgc2luY2UgMjAyNS0wMS0xMCAoaHR0cHM6Ly93d3cucHJvZHVjZXJlcG9ydC5jb20vYXJ0aWNsZS92aWV0bmFtZXNlLWR1cmlhbi1leHBvcnRzLWNoaW5hLWhhbHRlZC1vdmVyLW1pc3NpbmctdGVzdC1yZXBvcnRzKTsgcmVwb3J0IEtOLTI2MDkyOS0wMDcxIG9mIGxhYiBMQUItVk4tMTE4LCBzaWduZWQgd2l0aCBrZXkgTEFCLVZOLTExOC5rMSBoZWxkIGJ5IHRoZSBsYWIgb24gMjAyNi0wOS0yOVQwODo0MDowMFosIFNIQS0yNTYgNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZiwganVkZ2VkIGFnYWluc3QgdGhlIENOIG1hcmtldCdzIGxpbWl0cyIsImlkIjoidXJuOmFncml0cmFjZTpsb3Q6ZDgwNmFhNmQ5NjYzODVmZjlhNGZmNzhkNTM3MTQzNTYjbGFiLWF1cmFtaW5lX28iLCJuYW1lIjoiYXVyYW1pbmVfbyBpbiB0aGUgbG90J3Mgc2FtcGxlcyIsInJlZmVyZW5jZUNyaXRlcmlhIjpbeyJpZCI6InVybjphZ3JpdHJhY2U6bWFya2V0LWxpbWl0OkNOOmF1cmFtaW5lX28iLCJuYW1lIjoiQ04gbWFya2V0J3MgbGltaXQgZm9yIGF1cmFtaW5lX28gKEF1cmFtaW5lIE8gaXMgYSBub24tZWRpYmxlIHN1YnN0YW5jZSBpbiBDaGluYSAoTWluaXN0cnkgb2YgSGVhbHRoIGxpc3QsIDIwMDgpOiBubyBsZXZlbCBpcyBwZXJtaXR0ZWQ7IEdBQ0MgcmVxdWlyZXMgYW4gYXVyYW1pbmUgTyB0ZXN0IHJlcG9ydCB3aXRoIGV2ZXJ5IGR1cmlhbiBzaGlwbWVudCBzaW5jZSAyMDI1LTAxLTEwIChodHRwczovL3d3dy5wcm9kdWNlcmVwb3J0LmNvbS9hcnRpY2xlL3ZpZXRuYW1lc2UtZHVyaWFuLWV4cG9ydHMtY2hpbmEtaGFsdGVkLW92ZXItbWlzc2luZy10ZXN0LXJlcG9ydHMpKSIsInR5cGUiOlsiQ3JpdGVyaW9uIl19XSwidHlwZSI6WyJDbGFpbSJdfSx7ImNsYWltRGF0ZSI6IjIwMjYtMDktMjkiLCJjbGFpbWVkUGVyZm9ybWFuY2UiOlt7InNjb3JlIjp7ImNvZGUiOiJwYXNzIiwiZGVmaW5pdGlvbiI6ImV2ZXJ5IHNhbXBsZSB3aXRoaW4gdGhlIENOIG1hcmtldCdzIGxpbWl0In19LHsibWVhc3VyZSI6eyJ1bml0IjoiTkEiLCJ2YWx1ZSI6MC4wMTh9LCJtZXRyaWMiOnsiaWQiOiJodHRwczovL3ZvY2FidWxhcnkudW5jZWZhY3Qub3JnL3BlcmZvcm1hbmNlLW1ldHJpY3MvY2hlbWljYWwtY29udGFtaW5hbnQtbGV2ZWwiLCJuYW1lIjoiQ2hlbWljYWwgQ29udGFtaW5hbnQgTGV2ZWwiLCJ0eXBlIjpbIlBlcmZvcm1hbmNlTWV0cmljIl19fV0sImNvbmZvcm1pdHlUb3BpYyI6W3siaWQiOiJodHRwczovL3ZvY2FidWxhcnkudW5jZWZhY3Qub3JnL2NvbmZvcm1pdHktdG9waWNzL3Nhbml0YXJ5LWFuZC1waHl0b3Nhbml0YXJ5IiwibmFtZSI6IlNhbml0YXJ5IGFuZCBQaHl0b3Nhbml0YXJ5IE1lYXN1cmVzIiwidHlwZSI6WyJDb25mb3JtaXR5VG9waWMiXX1dLCJkZXNjcmlwdGlvbiI6ImNhZG1pdW06IDEgc2FtcGxlcywgZGV0ZWN0ZWQgaW4gMTsgbGltaXQ6IEdCIDI3NjItMjAyMiBOYXRpb25hbCBmb29kIHNhZmV0eSBzdGFuZGFyZDogbWF4aW11bSBsZXZlbHMgb2YgY29udGFtaW5hbnRzIGluIGZvb2RzLCA0LjIgY2FkbWl1bSwgZnJlc2ggZnJ1aXQgMC4wNSBtZy9rZyAocHVibGlzaGVkIDIwMjItMDYtMzAsIGluIGZvcmNlIDIwMjMtMDYtMzApOyByZXBvcnQgS04tMjYwOTI5LTAwNzEgb2YgbGFiIExBQi1WTi0xMTgsIHNpZ25lZCB3aXRoIGtleSBMQUItVk4tMTE4LmsxIGhlbGQgYnkgdGhlIGxhYiBvbiAyMDI2LTA5LTI5VDA4OjQwOjAwWiwgU0hBLTI1NiA1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmLCBqdWRnZWQgYWdhaW5zdCB0aGUgQ04gbWFya2V0J3MgbGltaXRzIiwiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdDpkODA2YWE2ZDk2NjM4NWZmOWE0ZmY3OGQ1MzcxNDM1NiNsYWItY2FkbWl1bSIsIm5hbWUiOiJjYWRtaXVtIGluIHRoZSBsb3QncyBzYW1wbGVzIiwicmVmZXJlbmNlQ3JpdGVyaWEiOlt7ImlkIjoidXJuOmFncml0cmFjZTptYXJrZXQtbGltaXQ6Q046Y2FkbWl1bSIsIm5hbWUiOiJDTiBtYXJrZXQncyBsaW1pdCBmb3IgY2FkbWl1bSAoR0IgMjc2Mi0yMDIyIE5hdGlvbmFsIGZvb2Qgc2FmZXR5IHN0YW5kYXJkOiBtYXhpbXVtIGxldmVscyBvZiBjb250YW1pbmFudHMgaW4gZm9vZHMsIDQuMiBjYWRtaXVtLCBmcmVzaCBmcnVpdCAwLjA1IG1nL2tnIChwdWJsaXNoZWQgMjAyMi0wNi0zMCwgaW4gZm9yY2UgMjAyMy0wNi0zMCkpIiwidHlwZSI6WyJDcml0ZXJpb24iXX1dLCJ0eXBlIjpbIkNsYWltIl19LHsiY2xhaW1EYXRlIjoiMjAyNi0wOS0yOSIsImNsYWltZWRQZXJmb3JtYW5jZSI6W3sic2NvcmUiOnsiY29kZSI6InBhc3MiLCJkZWZpbml0aW9uIjoiZXZlcnkgc2FtcGxlIG1hdGNoZWQgdGhlIGNsYWltZWQgcmVnaW9uIn19XSwiY29uZm9ybWl0eVRvcGljIjpbeyJpZCI6Imh0dHBzOi8vdm9jYWJ1bGFyeS51bmNlZmFjdC5vcmcvY29uZm9ybWl0eS10b3BpY3Mvb3JpZ2luLXRyYWNraW5nIiwibmFtZSI6Ik9yaWdpbiBUcmFja2luZyIsInR5cGUiOlsiQ29uZm9ybWl0eVRvcGljIl19XSwiZGVzY3JpcHRpb24iOiJvcmlnaW5faXNvdG9wZXM6IDEgc2FtcGxlcyBjb21wYXJlZCB3aXRoIFRp4buBbiBHaWFuZywgMSBtYXRjaDsgcmVwb3J0IEtOLTI2MDkyOS0wMDcxIG9mIGxhYiBMQUItVk4tMTE4LCBzaWduZWQgd2l0aCBrZXkgTEFCLVZOLTExOC5rMSBoZWxkIGJ5IHRoZSBsYWIgb24gMjAyNi0wOS0yOVQwODo0MDowMFosIFNIQS0yNTYgNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZiwganVkZ2VkIGFnYWluc3QgdGhlIENOIG1hcmtldCdzIGxpbWl0cyIsImlkIjoidXJuOmFncml0cmFjZTpsb3Q6ZDgwNmFhNmQ5NjYzODVmZjlhNGZmNzhkNTM3MTQzNTYjbGFiLW9yaWdpbl9pc290b3BlcyIsIm5hbWUiOiJvcmlnaW4gaXNvdG9wZXMgb2YgdGhlIGxvdCdzIHNhbXBsZXMiLCJyZWZlcmVuY2VDcml0ZXJpYSI6W3siaWQiOiJ1cm46YWdyaXRyYWNlOm9yaWdpbi10ZXN0OkNOIiwibmFtZSI6Imlzb3RvcGUgY29tcGFyaXNvbiB3aXRoIHRoZSBjbGFpbWVkIGdyb3dpbmcgcmVnaW9uLCBmb3IgdGhlIENOIG1hcmtldCIsInR5cGUiOlsiQ3JpdGVyaW9uIl19XSwidHlwZSI6WyJDbGFpbSJdfV0sInByb2R1Y2VkQXRGYWNpbGl0eSI6eyJpZCI6InVybjphZ3JpdHJhY2U6bG9jOlZOLVRHUEgtMDIxIiwiaWRTY2hlbWUiOnsiaWQiOiJ1cm46YWdyaXRyYWNlOmxvYyIsIm5hbWUiOiJDcm9wUGF0aCBmYWNpbGl0eSBjb2RlcyIsInR5cGUiOlsiSWRlbnRpZmllclNjaGVtZSJdfSwibmFtZSI6IlTDom4gUGjDuiIsInJlZ2lzdGVyZWRJZCI6IlZOLVRHUEgtMDIxIiwidHlwZSI6WyJGYWNpbGl0eSJdfSwicHJvZHVjdENhdGVnb3J5IjpbeyJjb2RlIjoiMDEzMTkiLCJuYW1lIjoiT3RoZXIgdHJvcGljYWwgYW5kIHN1YnRyb3BpY2FsIGZydWl0cywgbi5lLmMuIiwic2NoZW1lSWQiOiJodHRwczovL3Vuc3RhdHMudW4ub3JnL3Vuc2QvY2xhc3NpZmljYXRpb25zL0Vjb24vY3BjLyIsInNjaGVtZU5hbWUiOiJVTiBDZW50cmFsIFByb2R1Y3QgQ2xhc3NpZmljYXRpb24gKENQQykifV0sInByb2R1Y3Rpb25EYXRlIjoiMjAyNi0wOS0yNyIsInJlbGF0ZWREb2N1bWVudCI6W3sibGlua05hbWUiOiJQdWJsaWMgbG90IHJlY29yZCIsImxpbmtUeXBlIjoiaHR0cHM6Ly9nczEub3JnL3ZvYy9waXAiLCJsaW5rVVJMIjoiaHR0cHM6Ly90eG5nLnRoZWlvLnZuL3ZpL2wvZDgwNmFhNmQ5NjYzODVmZjlhNGZmNzhkNTM3MTQzNTYiLCJtZWRpYVR5cGUiOiJ0ZXh0L2h0bWwifSx7ImRpZ2VzdE11bHRpYmFzZSI6InVFaUFPclE2TVlsMnZha3NLVkY1WkhvU3hCbnlnSFZDb2R5eWducTBFbFgzM0NBIiwibGlua05hbWUiOiJFUENJUyAyLjAgZXZlbnRzIG9mIHRoZSBsb3QiLCJsaW5rVHlwZSI6Imh0dHBzOi8vZ3MxLm9yZy92b2MvdHJhY2VhYmlsaXR5IiwibGlua1VSTCI6Imh0dHBzOi8vdHhuZy50aGVpby52bi92MS9wdWJsaWMvbG90cy9kODA2YWE2ZDk2NjM4NWZmOWE0ZmY3OGQ1MzcxNDM1Ni9lcGNpcy5qc29ubGQiLCJtZWRpYVR5cGUiOiJhcHBsaWNhdGlvbi9sZCtqc29uIn0seyJkaWdlc3RNdWx0aWJhc2UiOiJ1RWlBMlJWQ0pDX0k4eHlnM0t6S1JqbTRoNWVZWEtSbW9sdzJVdTFOWFFkNTJBQSIsImxpbmtOYW1lIjoiVU5UUCBmYWNpbGl0eSByZWNvcmQgb2YgdGhlIHBhY2tpbmcgZmFjaWxpdHkiLCJsaW5rVHlwZSI6Imh0dHBzOi8vdGVzdC51bmNlZmFjdC5vcmcvdm9jYWJ1bGFyeS9saW5rVHlwZXMvZGZyIiwibGlua1VSTCI6Imh0dHBzOi8vdHhuZy50aGVpby52bi92MS9wdWJsaWMvbG90cy9kODA2YWE2ZDk2NjM4NWZmOWE0ZmY3OGQ1MzcxNDM1Ni9mYWNpbGl0eS1yZWNvcmQiLCJtZWRpYVR5cGUiOiJhcHBsaWNhdGlvbi92Yytqd3QifV0sInR5cGUiOlsiUHJvZHVjdCJdfSwiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdC1wYXNzcG9ydDpkODA2YWE2ZDk2NjM4NWZmOWE0ZmY3OGQ1MzcxNDM1NiIsImlzc3VlciI6eyJpZCI6ImRpZDp3ZWI6dHhuZy50aGVpby52bjp2bi10Z3BoLTAyMSIsIm5hbWUiOiJUw6JuIFBow7oiLCJ0eXBlIjpbIkNyZWRlbnRpYWxJc3N1ZXIiXX0sIm5hbWUiOiJEaWdpdGFsIFByb2R1Y3QgUGFzc3BvcnQgb2YgbG90IExPLTI2MDkyOC0wMTQiLCJ0eXBlIjpbIkRpZ2l0YWxQcm9kdWN0UGFzc3BvcnQiLCJWZXJpZmlhYmxlQ3JlZGVudGlhbCJdLCJ2YWxpZEZyb20iOiIyMDI2LTA5LTI5VDA4OjQxOjAwWiJ9.9Ppq2Pp20eq-AisObnDtdfuLBCyVn5R3gHyk39Om5bAQTrioPz1xN1s2DrbTB_jH-xHR2vSa0UPf-IT7Umpohw",
                "x-sdk-example": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSNrZXktMSIsInR5cCI6InZjK2p3dCJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiLCJodHRwczovL3Rlc3QudW5jZWZhY3Qub3JnL3ZvY2FidWxhcnkvdW50cC9kcHAvMC42LjEvIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImdyYW51bGFyaXR5TGV2ZWwiOiJiYXRjaCIsImlkIjoidXJuOmFncml0cmFjZTpsb3Q6MDc0ZWIwOWIzNzFmYzcxYzM4MGRhMjM1YWVhOWMxNGEiLCJwcm9kdWN0Ijp7ImJhdGNoTnVtYmVyIjoiTE8tMjYwOTI4LTAxNCIsImNoYXJhY3RlcmlzdGljcyI6eyJmcnVpdENvdW50IjoxMjMsImdyb3dpbmdBcmVhIjp7ImNvZGUiOiJWTi1UR09SLTAzODciLCJsb2NhbGl0eSI6Ik5nxakgSGnhu4dwLCBDYWkgTOG6rXksIFRp4buBbiBHaWFuZyJ9LCJuZXRNYXNzIjp7InR5cGUiOlsiTWVhc3VyZSJdLCJ1bml0IjoiS0dNIiwidmFsdWUiOjM0OS42fSwidHlwZSI6WyJDaGFyYWN0ZXJpc3RpY3MiXSwidmFyaWV0eSI6IlJpNiJ9LCJjb3VudHJ5T2ZQcm9kdWN0aW9uIjoiVk4iLCJmdXJ0aGVySW5mb3JtYXRpb24iOlt7ImxpbmtOYW1lIjoiUHVibGljIGxvdCByZWNvcmQiLCJsaW5rVHlwZSI6InRleHQvaHRtbCIsImxpbmtVUkwiOiJodHRwczovL3R4bmcudGhlaW8udm4vdmkvbC8wNzRlYjA5YjM3MWZjNzFjMzgwZGEyMzVhZWE5YzE0YSIsInR5cGUiOlsiTGluayJdfV0sImlkIjoidXJuOmFncml0cmFjZTpsb3Q6TE8tMjYwOTI4LTAxNCIsIm5hbWUiOiJEdXJpYW4gUmk2IiwicHJvZHVjZWRBdEZhY2lsaXR5Ijp7ImlkIjoidXJuOmFncml0cmFjZTpsb2M6Vk4tVEdQSC0wMjEiLCJuYW1lIjoiVMOibiBQaMO6In0sInByb2R1Y3Rpb25EYXRlIjoiMjAyNi0wOS0yNyIsInR5cGUiOlsiUHJvZHVjdCJdfSwidHJhY2VhYmlsaXR5SW5mb3JtYXRpb24iOlt7InRyYWNlYWJpbGl0eUV2ZW50IjpbeyJlbmNyeXB0aW9uTWV0aG9kIjoibm9uZSIsImhhc2hEaWdlc3QiOiI0YWVlNTIxYzRhOTEyODE0MzA2Y2U2MWJiNGFiMjk0MzEyMTRmZTk4MTMzZDRmMDY1MzU2NWZhZTM3OGZhMTAwIiwiaGFzaE1ldGhvZCI6IlNIQS0yNTYiLCJsaW5rTmFtZSI6IkVQQ0lTIDIuMCBldmVudHMgb2YgdGhlIGxvdCIsImxpbmtUeXBlIjoiYXBwbGljYXRpb24vbGQranNvbiIsImxpbmtVUkwiOiJodHRwczovL3R4bmcudGhlaW8udm4vdjEvcHVibGljL2xvdHMvMDc0ZWIwOWIzNzFmYzcxYzM4MGRhMjM1YWVhOWMxNGEvZXBjaXMuanNvbmxkIiwidHlwZSI6WyJTZWN1cmVMaW5rIiwiTGluayJdfV0sInR5cGUiOlsiVHJhY2VhYmlsaXR5UGVyZm9ybWFuY2UiXSwidmFsdWVDaGFpblByb2Nlc3MiOiJoYXJ2ZXN0LCBtZWFzdXJlbWVudCwgcGFja2luZyBhbmQgc2hpcHBpbmcgb2YgdGhlIGxvdCJ9XSwidHlwZSI6WyJQcm9kdWN0UGFzc3BvcnQiXX0sImlkIjoidXJuOmFncml0cmFjZTpsb3QtcGFzc3BvcnQ6MDc0ZWIwOWIzNzFmYzcxYzM4MGRhMjM1YWVhOWMxNGEiLCJpc3N1ZXIiOnsiaWQiOiJkaWQ6d2ViOnR4bmcudGhlaW8udm46dGFucGh1IiwibmFtZSI6IlTDom4gUGjDuiIsInR5cGUiOlsiQ3JlZGVudGlhbElzc3VlciJdfSwidHlwZSI6WyJEaWdpdGFsUHJvZHVjdFBhc3Nwb3J0IiwiVmVyaWZpYWJsZUNyZWRlbnRpYWwiXSwidmFsaWRGcm9tIjoiMjAyNi0wOS0zMFQwNzo0MDowMFoifQ.gip_kxOtNSvzPm4BapjXtFRkbxM2Ajb8giNAczwJsAgS81bIola3xhMbkIU-Z8ucIfXLtWk-bnROtqLFk-IcMw"
              }
            }
          },
          "404": {
            "description": "No credential: every id the public lot route answers 404 for, a public lot that was not sealed with public documents, and a lot whose issuer key was revoked. Every such id gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "X3 (#44): the lot's UNTP Digital Product Passport (UNTP 0.6.1) as a VC 2.0 credential secured with VC-JOSE (W3C Recommendation 2025-05-15): a compact JWS (ES256, `typ` `vc+jwt`, `kid` the issuer key's DID URL), issued and verified once when the lot was sealed, with the facility's issuer key named by the public lot record's `issuer`. It verifies with that key in the facility's `/{slug}/did.json` (/developers/downloads/verify.md). A download named `untp-dpp-<lot code>.jwt`. Its lab conformity claims are made only from a report the public lab step accepts (ADR 0001: its key not revoked for compromise, from the lab the sampling assigned). Withdrawn (404) once that key is revoked for compromise, or once the lab key its claims cite is. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the visibility lookups of the public record, then one statement that returns the text stored when the lot was sealed; nothing is decoded, verified or signed per request. Cross-origin readable (`Access-Control-Allow-Origin: *`), like the DID document, so a verifier's page can fetch it."
      }
    },
    "/v1/public/lots/{publicId}/lab-credential": {
      "get": {
        "operationId": "getPublicLotLabCredential",
        "summary": "Public UNTP conformity credential of a sealed lot's lab",
        "description": "#142: the UNTP Digital Conformity Credential (UNTP DCC 0.6.1) of the lab whose report the lot's credential claims from, as a VC 2.0 credential secured with VC-JOSE (W3C Recommendation 2025-05-15): a compact JWS (ES256, `typ` `vc+jwt`), issued in the lab's name (`issuer.id` `did:web:<domain>:labs:<lab code>`) and verified once when the lot was sealed. It is issued only for a report the lab entered in its CropPath portal, signed with that report's own key, the key CropPath holds for the lab's portal users (`kid` `<lab did>#<kid>`), so its custody is the report's `key_custody` `server`; a report the lab signed with its own key gets none. It verifies with that key in the lab's `/labs/{code}/did.json` (/developers/downloads/verify.md). The lot's credential links it from each lab claim: as `evidence` with its `digestMultibase` in a UNTP 0.7.0 passport (#162), as `conformityEvidence` with its SHA-256 in a 0.6.1 one. A download named `untp-dcc-<lot code>.jwt`. Withdrawn (404) once the lab key that signed it is revoked for compromise (the lot's credential is then withdrawn too); the facility's issuer key does not sign it, so that key's revocation leaves it. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the visibility lookups of the public record, then one statement that returns the text stored when the lot was sealed; nothing is decoded, verified or signed per request. Cross-origin readable (`Access-Control-Allow-Origin: *`), like the DID document, so a verifier's page can fetch it. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          }
        ],
        "responses": {
          "200": {
            "description": "The stored compact JWS.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"untp-dcc-<lot code>.jwt\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/vc+jwt": {
                "schema": {
                  "$ref": "#/components/schemas/PublicConformityCredential"
                },
                "example": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOmxhYnM6TEFCLVZOLTExOCNMQUItVk4tMTE4LnBvcnRhbCIsInR5cCI6InZjK2p3dCJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiLCJodHRwczovL3Rlc3QudW5jZWZhY3Qub3JnL3ZvY2FidWxhcnkvdW50cC9kY2MvMC42LjEvIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImFzc2Vzc21lbnQiOlt7ImFzc2Vzc2VkUHJvZHVjdCI6W3sicHJvZHVjdCI6eyJiYXRjaE51bWJlciI6IkxPLTI2MDkyOC0wMTQiLCJpZCI6InVybjphZ3JpdHJhY2U6bG90OkxPLTI2MDkyOC0wMTQiLCJuYW1lIjoiRHVyaWFuIFJpNiJ9LCJ0eXBlIjpbIlByb2R1Y3RWZXJpZmljYXRpb24iXX1dLCJhc3Nlc3NtZW50RGF0ZSI6IjIwMjYtMDktMjkiLCJjb25mb3JtYW5jZSI6dHJ1ZSwiY29uZm9ybWl0eVRvcGljIjoiZ292ZXJuYW5jZS5jb21wbGlhbmNlIiwiZGVzY3JpcHRpb24iOiJhdXJhbWluZV9vOiAxIHNhbXBsZXMsIGRldGVjdGVkIGluIDA7IGxpbWl0OiBBdXJhbWluZSBPIGlzIGEgbm9uLWVkaWJsZSBzdWJzdGFuY2UgaW4gQ2hpbmEgKE1pbmlzdHJ5IG9mIEhlYWx0aCBsaXN0LCAyMDA4KTogbm8gbGV2ZWwgaXMgcGVybWl0dGVkOyBHQUNDIHJlcXVpcmVzIGFuIGF1cmFtaW5lIE8gdGVzdCByZXBvcnQgd2l0aCBldmVyeSBkdXJpYW4gc2hpcG1lbnQgc2luY2UgMjAyNS0wMS0xMCAoaHR0cHM6Ly93d3cucHJvZHVjZXJlcG9ydC5jb20vYXJ0aWNsZS92aWV0bmFtZXNlLWR1cmlhbi1leHBvcnRzLWNoaW5hLWhhbHRlZC1vdmVyLW1pc3NpbmctdGVzdC1yZXBvcnRzKSIsImlkIjoidXJuOmFncml0cmFjZTpsYWItcmVwb3J0OkxBQi1WTi0xMTg6S04tMjYwOTI5LTAwNzEjYXVyYW1pbmVfbyIsIm5hbWUiOiJhdXJhbWluZV9vIiwidHlwZSI6WyJDb25mb3JtaXR5QXNzZXNzbWVudCIsIkRlY2xhcmF0aW9uIl19LHsiYXNzZXNzZWRQcm9kdWN0IjpbeyJwcm9kdWN0Ijp7ImJhdGNoTnVtYmVyIjoiTE8tMjYwOTI4LTAxNCIsImlkIjoidXJuOmFncml0cmFjZTpsb3Q6TE8tMjYwOTI4LTAxNCIsIm5hbWUiOiJEdXJpYW4gUmk2In0sInR5cGUiOlsiUHJvZHVjdFZlcmlmaWNhdGlvbiJdfV0sImFzc2Vzc21lbnREYXRlIjoiMjAyNi0wOS0yOSIsImNvbmZvcm1hbmNlIjp0cnVlLCJjb25mb3JtaXR5VG9waWMiOiJnb3Zlcm5hbmNlLmNvbXBsaWFuY2UiLCJkZWNsYXJlZFZhbHVlIjpbeyJtZXRyaWNOYW1lIjoiY2FkbWl1bSwgc2FtcGxlIDEiLCJtZXRyaWNWYWx1ZSI6eyJ0eXBlIjpbIk1lYXN1cmUiXSwidW5pdCI6Ik5BIiwidmFsdWUiOjAuMDE4fSwidHlwZSI6WyJNZXRyaWMiXX1dLCJkZXNjcmlwdGlvbiI6ImNhZG1pdW06IDEgc2FtcGxlcywgZGV0ZWN0ZWQgaW4gMTsgbGltaXQ6IEdCIDI3NjItMjAyMiBOYXRpb25hbCBmb29kIHNhZmV0eSBzdGFuZGFyZDogbWF4aW11bSBsZXZlbHMgb2YgY29udGFtaW5hbnRzIGluIGZvb2RzLCA0LjIgY2FkbWl1bSwgZnJlc2ggZnJ1aXQgMC4wNSBtZy9rZyAocHVibGlzaGVkIDIwMjItMDYtMzAsIGluIGZvcmNlIDIwMjMtMDYtMzApIiwiaWQiOiJ1cm46YWdyaXRyYWNlOmxhYi1yZXBvcnQ6TEFCLVZOLTExODpLTi0yNjA5MjktMDA3MSNjYWRtaXVtIiwibmFtZSI6ImNhZG1pdW0iLCJ0eXBlIjpbIkNvbmZvcm1pdHlBc3Nlc3NtZW50IiwiRGVjbGFyYXRpb24iXX1dLCJhc3Nlc3NtZW50TGV2ZWwiOiJVbnNwZWNpZmllZCIsImFzc2Vzc29yTGV2ZWwiOiIzcmRQYXJ0eSIsImF0dGVzdGF0aW9uVHlwZSI6InRlc3RpbmciLCJkZXNjcmlwdGlvbiI6IlJlc3VsdHMgb2YgcmVwb3J0IEtOLTI2MDkyOS0wMDcxIG9mIGxhYiBMQUItVk4tMTE4IG9uIHRoZSBzYW1wbGVzIGRyYXduIGZyb20gbG90IExPLTI2MDkyOC0wMTQsIGp1ZGdlZCBhZ2FpbnN0IHRoZSBDTiBtYXJrZXQncyBsaW1pdHMuIEVudGVyZWQgYnkgdGhlIGxhYidzIHBvcnRhbCB1c2VycyBhbmQgc2lnbmVkIG9uIDIwMjYtMDktMjlUMDg6NDE6MDBaIHdpdGgga2V5IExBQi1WTi0xMTgucG9ydGFsLCBoZWxkIGJ5IHRoZSBwbGF0Zm9ybSBmb3IgdGhlIGxhYidzIHBvcnRhbCB1c2Vycywgbm90IGJ5IHRoZSBsYWI7IFNIQS0yNTYgb2YgdGhlIHJlcG9ydCA1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmNWY1ZjVmLiIsImlkIjoidXJuOmFncml0cmFjZTpsYWItcmVwb3J0OkxBQi1WTi0xMTg6S04tMjYwOTI5LTAwNzEiLCJpc3N1ZWRUb1BhcnR5Ijp7ImlkIjoidXJuOmFncml0cmFjZTpsb2M6Vk4tVEdQSC0wMjEiLCJuYW1lIjoiVMOibiBQaMO6In0sIm5hbWUiOiJMYWIgcmVwb3J0IEtOLTI2MDkyOS0wMDcxIG9mIGxvdCBMTy0yNjA5MjgtMDE0IiwidHlwZSI6WyJDb25mb3JtaXR5QXR0ZXN0YXRpb24iLCJBdHRlc3RhdGlvbiJdfSwiaWQiOiJ1cm46YWdyaXRyYWNlOmxhYi1jb25mb3JtaXR5OmE2OWQ2OTk5ZWQ5NTRhOTNkODI5NTQ1NDAzZWMzOGQyIiwiaXNzdWVyIjp7ImlkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOmxhYnM6TEFCLVZOLTExOCIsIm5hbWUiOiJMQUItVk4tMTE4IiwidHlwZSI6WyJDcmVkZW50aWFsSXNzdWVyIl19LCJ0eXBlIjpbIkRpZ2l0YWxDb25mb3JtaXR5Q3JlZGVudGlhbCIsIlZlcmlmaWFibGVDcmVkZW50aWFsIl0sInZhbGlkRnJvbSI6IjIwMjYtMDktMjlUMDg6NDE6MDBaIn0.nJawXQrDNUmxDrpWOIsW2MoW85f_o3lBpAW3pGkZ8NE2RtojH7zA7fVgGm2PHX7suUyWECRJvqmvfw32vjwaKg"
              }
            }
          },
          "404": {
            "description": "No lab credential: every id the public lot route answers 404 for, a public lot that was not sealed with one (no lab report claimed at the seal, or one the lab signed with its own key), and a lot whose lab key that signed it was revoked for compromise. Every such id gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/public/lots/{publicId}/facility-record": {
      "get": {
        "operationId": "getPublicLotFacilityRecord",
        "summary": "Public UNTP facility record of a sealed lot's packing facility",
        "description": "#162: the packing facility's UNTP Digital Facility Record (UNTP 0.7.0) issued when the lot was sealed, as a VC 2.0 credential secured with VC-JOSE (W3C Recommendation 2025-05-15): a compact JWS (ES256, `typ` `vc+jwt`) signed with the same facility issuer key as the lot's passport, which links it as a related document (link type `https://test.uncefact.org/vocabulary/linkTypes/dfr`) with the `digestMultibase` of the text served here. It describes the facility as it was at the seal: its name, its code (`urn:agritrace:loc:<code>`, the passport's `producedAtFacility`), its locality (no street address, postal code or coordinates), its GLN when it has one, each packing house registration code the published code lists match for a destination market on a list that is not stale (with the list's import date and the SHA-256 of the authority's file), and its process category (ISIC Rev. 4 0163, post-harvest crop activities). It verifies with that key in the facility's `/{slug}/did.json` (/developers/downloads/verify.md). A download named `untp-dfr-<lot code>.jwt`. Withdrawn (404) once that key is revoked for compromise, with the lot's passport. A lot sealed before #162 has none. Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the visibility lookups of the public record, then one statement that returns the text stored when the lot was sealed; nothing is decoded, verified or signed per request. Cross-origin readable (`Access-Control-Allow-Origin: *`), like the DID document, so a verifier's page can fetch it. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          }
        ],
        "responses": {
          "200": {
            "description": "The stored compact JWS.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"untp-dfr-<lot code>.jwt\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "`*`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/vc+jwt": {
                "schema": {
                  "$ref": "#/components/schemas/PublicCredential"
                },
                "example": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnZuLXRncGgtMDIxI2tleS0xIiwidHlwIjoidmMrand0In0.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiLCJodHRwczovL3ZvY2FidWxhcnkudW5jZWZhY3Qub3JnL3VudHAvMC43LjAvY29udGV4dC8iXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiYWRkcmVzcyI6eyJhZGRyZXNzQ291bnRyeSI6eyJjb3VudHJ5Q29kZSI6IlZOIiwiY291bnRyeU5hbWUiOiJWaWV0IE5hbSJ9LCJhZGRyZXNzTG9jYWxpdHkiOiJDYWkgTOG6rXkiLCJhZGRyZXNzUmVnaW9uIjoiVGnhu4FuIEdpYW5nIiwicG9zdGFsQ29kZSI6IiIsInN0cmVldEFkZHJlc3MiOiIifSwiY291bnRyeU9mT3BlcmF0aW9uIjp7ImNvdW50cnlDb2RlIjoiVk4iLCJjb3VudHJ5TmFtZSI6IlZpZXQgTmFtIn0sImRlc2NyaXB0aW9uIjoiUGFja2luZyBmYWNpbGl0eSBWTi1UR1BILTAyMSBpbiBDYWkgTOG6rXksIFRp4buBbiBHaWFuZywgVmlldCBOYW0uIiwiaWQiOiJ1cm46YWdyaXRyYWNlOmxvYzpWTi1UR1BILTAyMSIsImlkU2NoZW1lIjp7ImlkIjoidXJuOmFncml0cmFjZTpsb2MiLCJuYW1lIjoiQ3JvcFBhdGggZmFjaWxpdHkgY29kZXMiLCJ0eXBlIjpbIklkZW50aWZpZXJTY2hlbWUiXX0sImxvY2F0aW9uSW5mb3JtYXRpb24iOnt9LCJuYW1lIjoiVMOibiBQaMO6IiwicHJvY2Vzc0NhdGVnb3J5IjpbeyJjb2RlIjoiMDE2MyIsIm5hbWUiOiJQb3N0LWhhcnZlc3QgY3JvcCBhY3Rpdml0aWVzIiwic2NoZW1lSWQiOiJodHRwczovL3Vuc3RhdHMudW4ub3JnL3Vuc2QvY2xhc3NpZmljYXRpb25zL0Vjb24vaXNpYyIsInNjaGVtZU5hbWUiOiJJbnRlcm5hdGlvbmFsIFN0YW5kYXJkIEluZHVzdHJpYWwgQ2xhc3NpZmljYXRpb24gb2YgQWxsIEVjb25vbWljIEFjdGl2aXRpZXMgKElTSUMpLCBSZXZpc2lvbiA0In1dLCJyZWdpc3RlcmVkSWQiOiJWTi1UR1BILTAyMSIsInR5cGUiOlsiRmFjaWxpdHkiXX0sImlkIjoidXJuOmFncml0cmFjZTpmYWNpbGl0eS1yZWNvcmQ6ZDgwNmFhNmQ5NjYzODVmZjlhNGZmNzhkNTM3MTQzNTYiLCJpc3N1ZXIiOnsiaWQiOiJkaWQ6d2ViOnR4bmcudGhlaW8udm46dm4tdGdwaC0wMjEiLCJuYW1lIjoiVMOibiBQaMO6IiwidHlwZSI6WyJDcmVkZW50aWFsSXNzdWVyIl19LCJuYW1lIjoiRGlnaXRhbCBGYWNpbGl0eSBSZWNvcmQgb2YgVMOibiBQaMO6IiwidHlwZSI6WyJEaWdpdGFsRmFjaWxpdHlSZWNvcmQiLCJWZXJpZmlhYmxlQ3JlZGVudGlhbCJdLCJ2YWxpZEZyb20iOiIyMDI2LTA5LTI5VDA4OjQxOjAwWiJ9.sBe6_TaAybwTWdtpSCSMvdVbbGWR7SpzLe8_fOc6w6IoH0VWXkzkVN06GKF_-3UiEn3yBu2-aAgnKuBZV7cm4w"
              }
            }
          },
          "404": {
            "description": "No facility record: every id the public lot route answers 404 for, a public lot that was not sealed (or sealed before #162, or without public documents), and a lot whose issuer key was revoked for compromise. Every such id gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/public/reports/challenge": {
      "get": {
        "operationId": "getReportChallenge",
        "summary": "A proof-of-work challenge for a public mismatch report",
        "description": "Anonymous and tenant-less (#46, MO decision (a): no third-party challenge). The backend keeps nothing per challenge; it is signed and expires after `expires_in` seconds. Not audited (a read). Rate limited per client by the /v1/public/* bucket.",
        "tags": [
          "public"
        ],
        "security": [],
        "responses": {
          "200": {
            "description": "A new challenge.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReportChallenge"
                },
                "example": {
                  "challenge": "9f1c2e7a5b3d4c6e8f0a1b2c3d4e5f60.18.1790000300.3b0f6a1c9d2e4f5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c",
                  "difficulty": 18,
                  "expires_in": 300
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many requests from this client address: the /v1/public/* bucket (bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer. Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/reports": {
      "post": {
        "operationId": "fileReport",
        "summary": "Report a fruit that does not match its public record",
        "description": "Anonymous and tenant-less (#46): a request carrying a session, token, cookie or X-Tenant is treated exactly like an anonymous one. In order: the /v1/public/* bucket, the report bucket (5 reports an hour per client, before the body is read), the body (ReportSubmission), the proof of work (a ReportChallenge this backend issued, at its current difficulty, not expired, solved), the reported fruit's bucket (20 reports an hour per public id, whoever sends them), then the fruit, looked up exactly as the public fruit record does: any id that is not a public fruit's answers that record's 404. The report is stored with its challenge, which then cannot file another. An open report holds the fruit's lot (ADR 0001): its displayed tier is capped at Self-declared and the lot and fruit records read `under_review` (or `on_hold` when another hold is open too) from the earliest open report, one hold however many reports are open, until staff resolve the last of them; resolution restores at most the sealed tier. The public records are cached up to 60 s, so the hold shows within that. Not audited (AUDIT_EXEMPT: the reports row is the record, and an anonymous route must not append to the audit log). Every answer is `no-store`. SELF-2-4 (#193): a report on a fruit of a company that is leaving CropPath or has left is refused 403 `company_read_only` (nothing is stored, the challenge stays unused): the company is read-only, so nobody could triage it, and its hold would cap the lot's displayed tier for good.",
        "tags": [
          "public"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReportSubmission"
              },
              "example": {
                "publicId": "73879f17d0930440809333f141385eb6",
                "category": "label_peeled",
                "note": "Tem bị bóc ở cuống.",
                "contact": "zalo 0901 234 567",
                "challenge": "9f1c2e7a5b3d4c6e8f0a1b2c3d4e5f60.18.1790000300.3b0f6a1c9d2e4f5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c",
                "solution": "184022"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The report was received.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReportReceipt"
                },
                "example": {
                  "status": "received",
                  "fruit": {
                    "status": "under_review",
                    "status_since": "2026-10-10T09:30:00+07:00",
                    "status_reason": null,
                    "tier": "self_declared"
                  },
                  "lot": {
                    "status": "under_review",
                    "status_since": "2026-10-10T09:30:00+07:00",
                    "status_reason": null,
                    "tier": "self_declared"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a field that does not fit ReportSubmission (the first one is named; an unknown field is refused), a challenge that does not verify (another backend's or forged, at another difficulty, expired or unsolved: ask for a new one), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "category": {
                    "value": {
                      "error": "invalid category",
                      "code": "invalid_category"
                    }
                  },
                  "note": {
                    "value": {
                      "error": "invalid note",
                      "code": "invalid_note"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: photo_sha",
                      "code": "unknown_fields"
                    }
                  },
                  "challenge": {
                    "value": {
                      "error": "invalid challenge",
                      "code": "invalid_challenge"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The fruit's company is leaving CropPath or has left (`company_read_only`): the report is refused and nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                  "code": "company_read_only"
                }
              }
            }
          },
          "404": {
            "description": "Not a public fruit: the public fruit record's own 404 (an unknown or malformed id, a lot's id, a fruit the record does not show). The id is never echoed; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: fruits",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The challenge already filed a report: ask for a new one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "challenge already used",
                  "code": "challenge_already_used"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many requests from this client address: the /v1/public/* bucket (bursts of 60, then 20 a second), the report bucket (5 reports an hour per client) or the reported fruit's bucket (20 reports an hour per public id). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer. Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/email/unsubscribe": {
      "post": {
        "operationId": "unsubscribeEmail",
        "summary": "Turn notification emails off with an email's link",
        "description": "#270. Every notification, alert and recall email carries the person's unsubscribe link, `/login#unsubscribe=<token>`; the page posts the token here. It turns that person's notification, alert and recall emails off (invitation and password emails are always sent) and does nothing else. The token is `<account id>.<company>.<signature>`, signed by the server for this purpose only; it needs no sign-in and does not expire. An invalid token is a 400 (nothing is looked up for it); a valid one answers 200 whether or not anything changed. Audited by the service itself (`email.unsubscribe`, in the company of the email) when the setting changed; a request that changes nothing writes no row. Anonymous. Rate limited per client before anything else (/v1/public/*, and the login bucket). Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "public"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EmailUnsubscribe"
              },
              "example": {
                "token": "12.coop-dl.4yGq3o0b1d0e7n2m8J5k9v6c3x1z0a2s4d6f8h0j2l4"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The person's notification emails are off.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EmailUnsubscribed"
                },
                "example": {
                  "notifications": false
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not exactly `{token}`, a token that is not valid, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "token": {
                    "value": {
                      "error": "token is required",
                      "code": "token_is_required"
                    }
                  },
                  "invalid": {
                    "value": {
                      "error": "invalid link",
                      "code": "invalid_link"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many requests from this client address: the /v1/public/* bucket (bursts of 60, then 20 a second) or the login bucket (bursts of 20, then one every 6 seconds), shared with sign-in. The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer. Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/reports": {
      "get": {
        "operationId": "listReports",
        "summary": "The tenant's public mismatch reports (staff triage)",
        "description": "Newest first, one page (`limit`, default 50, at most 200; `cursor` from the previous page), optionally only `open` or `resolved` ones and only one `category`, with the contact the visitor left (null once erased). Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant); other tenants' reports are never listed. Not audited (a read). `no-store`.",
        "tags": [
          "reports"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "report_triage"
            ]
          }
        ],
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "`open` or `resolved`.",
            "schema": {
              "type": "string",
              "enum": [
                "open",
                "resolved"
              ]
            },
            "example": "open"
          },
          {
            "name": "category",
            "in": "query",
            "required": false,
            "description": "Only reports of this category (ReportCategory).",
            "schema": {
              "$ref": "#/components/schemas/ReportCategory"
            },
            "example": "scanned_many"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of reports.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReportPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 12,
                      "fruit": {
                        "code": "Q-0928-014-0003",
                        "public_id": "73879f17d0930440809333f141385eb6"
                      },
                      "lot": {
                        "code": "LO-260928-014",
                        "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
                      },
                      "category": "label_peeled",
                      "note": "Tem bị bóc ở cuống.",
                      "contact": "zalo 0901 234 567",
                      "status": "open",
                      "outcome": null,
                      "created_at": 1790000000.5,
                      "resolved_at": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `status`, `category`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "value": {
                      "error": "bad status",
                      "code": "bad_status"
                    }
                  },
                  "category": {
                    "value": {
                      "error": "bad category",
                      "code": "bad_category"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/reports/{id}/resolve": {
      "post": {
        "operationId": "resolveReport",
        "summary": "Resolve a public mismatch report",
        "description": "Resolves one of the tenant's open reports with an outcome, once. When it was the lot's last open report, the lot's report hold clears: the lot is recomputed right after the commit and its pages leave `under_review`, with at most the sealed tier. Audited (`report.resolve`, in the same transaction; the contact is never in the audit row). Allowed for tenant_admin and platform_admin acting for the tenant; another tenant's report answers like a missing one.",
        "tags": [
          "reports"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "report_triage"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The report id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReportResolution"
              },
              "example": {
                "outcome": "unfounded"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The report, resolved.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Report"
                },
                "example": {
                  "id": 12,
                  "fruit": {
                    "code": "Q-0928-014-0003",
                    "public_id": "73879f17d0930440809333f141385eb6"
                  },
                  "lot": {
                    "code": "LO-260928-014",
                    "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
                  },
                  "category": "label_peeled",
                  "note": "Tem bị bóc ở cuống.",
                  "contact": "zalo 0901 234 567",
                  "status": "resolved",
                  "outcome": "unfounded",
                  "created_at": 1790000000.5,
                  "resolved_at": 1790003600.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or an outcome that is not one of ReportResolution's, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "outcome": {
                    "value": {
                      "error": "invalid outcome",
                      "code": "invalid_outcome"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: note",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such report of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The report is already resolved. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "report_already_resolved": {
                    "value": {
                      "error": "report already resolved",
                      "code": "report_already_resolved"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/close-check": {
      "get": {
        "operationId": "getLotCloseCheck",
        "summary": "A lot's close check",
        "description": "What the operator console's close dialog shows (O6, #64) before `POST /v1/lots/{lot}/close` and after it: the final counts, the measurement sessions still open or paused, the facility's active issuer key, the blockers (codes, in this order: `already_sealed`, `not_sealable`, `fruits_pending_review`, `session_open`, `envelopes_not_synced`, `no_issuer_key`, `lot_too_large`) and, once sealed, the seal with its external timestamp state. The close itself checks again what it refuses: the check is a view, not a lock. Seven statements whatever the lot's size. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's close check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotCloseCheck"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "status": "open",
                  "sealed": false,
                  "counts": {
                    "fruits": 128,
                    "pending_review": 0,
                    "awaiting_device": 1,
                    "quarantined_envelopes": 0,
                    "cartons": null
                  },
                  "sessions": {
                    "open": 1,
                    "paused": 0
                  },
                  "issuer_key": "did:web:txng.theio.vn:tanphu#key-1",
                  "timestamping": true,
                  "blockers": [
                    "session_open",
                    "envelopes_not_synced"
                  ],
                  "seal": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/fruits/{publicId}/recordings/{sha256}": {
      "get": {
        "operationId": "getPublicFruitRecording",
        "summary": "Original tap recording of a public fruit",
        "description": "U5 (#58): the original recording of a public fruit's knock, as stored: the WAV its knock envelope references by SHA-256 and its knocker uploaded, from which the fruit record's waveform is drawn. Served under exactly the public fruit record's visibility and only at the URL naming the blob's SHA-256 (the list's `recording_url`), so the bytes at a URL never change and a fruit measured again gets a new URL. Served only when the stored bytes still hash to it and form a plain RIFF/WAVE file (fmt, fact and data chunks only; a recording with any other chunk, such as LIST/INFO metadata, is never public). Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work and size: the fruit record's two visibility lookups and one statement for the recording's hash and size; an `If-None-Match` naming its ETag answers 304 without reading the blob; otherwise the client's download bucket (shared with the EPCIS download) takes one token per started KiB served (bursts of 32 MiB, then 64 KiB a second), then the blob (at most 1 MiB) is read. Byte ranges (RFC 9110, 14): Safari and iOS play an audio source only from a server that answers a byte range with 206, so ONE range of `bytes` (`a-b`, `a-` or the suffix `-n`) answers 206 with exactly those bytes and is charged only for them; a range that selects no byte is 416 and charges nothing; several ranges, another unit, a malformed value, or a Range whose `If-Range` is not the recording's ETag (compared strongly; a date never matches) get the whole recording (200).",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The fruit's public id. Any id that is not a public fruit's is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "5c1f0e2a9b7d4c3e8f6a1b2c3d4e5f60"
          },
          {
            "name": "sha256",
            "in": "path",
            "required": true,
            "description": "The recording's SHA-256 (64 lowercase hex), as the list's `recording_url` names it. Any other value is 404.",
            "schema": {
              "type": "string"
            },
            "example": "9f2c0d5ab1e7c3f4a6b8d0e2f4a6c8e0b2d4f6a8c0e2a4c6e8a0c2e4a6c8e0b2"
          },
          {
            "name": "If-None-Match",
            "in": "header",
            "required": false,
            "description": "An ETag of the recording (its SHA-256, quoted), a list of them or `*`; compared weakly (RFC 9110). When it names the recording's tag the answer is 304.",
            "schema": {
              "type": "string"
            },
            "example": "\"9f2c0d5ab1e7c3f4a6b8d0e2f4a6c8e0b2d4f6a8c0e2a4c6e8a0c2e4a6c8e0b2\""
          },
          {
            "name": "Range",
            "in": "header",
            "required": false,
            "description": "One byte range of the recording: `bytes=<first>-<last>`, `bytes=<first>-` or `bytes=-<suffix length>` (positions count from 0; a last position past the end is the end). Several ranges, another unit or a malformed value are ignored (200 with the whole recording).",
            "schema": {
              "type": "string"
            },
            "example": "bytes=0-1"
          },
          {
            "name": "If-Range",
            "in": "header",
            "required": false,
            "description": "The recording's ETag: the Range is honoured only when this is absent or names that ETag exactly (strong comparison); anything else, including a date, gets the whole recording.",
            "schema": {
              "type": "string"
            },
            "example": "\"9f2c0d5ab1e7c3f4a6b8d0e2f4a6c8e0b2d4f6a8c0e2a4c6e8a0c2e4a6c8e0b2\""
          }
        ],
        "responses": {
          "200": {
            "description": "The stored recording, byte for byte.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=31536000, immutable`: the URL names the bytes' hash. Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The recording's SHA-256 hex, quoted (a strong ETag).",
                "schema": {
                  "type": "string"
                }
              },
              "Accept-Ranges": {
                "description": "`bytes`: one byte range of the recording may be requested.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`inline; filename=\"recording-<first 16 hex digits of the hash>.wav\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Security-Policy": {
                "description": "`default-src 'none'; sandbox`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "audio/wav": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "audio/wav"
                },
                "example": "RIFF....WAVEfmt  ... (binary PCM WAV bytes)"
              }
            }
          },
          "206": {
            "description": "Partial content: the one byte range the `Range` header asks for, exactly those bytes of the stored recording (Content-Length is their count). Charged one download token per started KiB served.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=31536000, immutable`: the URL names the bytes' hash. Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The recording's SHA-256 hex, quoted (a strong ETag).",
                "schema": {
                  "type": "string"
                }
              },
              "Accept-Ranges": {
                "description": "`bytes`: one byte range of the recording may be requested.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Range": {
                "description": "`bytes <first>-<last>/<size>`: the positions served (inclusive) and the recording's size in bytes.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Disposition": {
                "description": "`inline; filename=\"recording-<first 16 hex digits of the hash>.wav\"`.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Security-Policy": {
                "description": "`default-src 'none'; sandbox`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "audio/wav": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "audio/wav"
                },
                "example": "RI"
              }
            }
          },
          "304": {
            "description": "Not modified: the request's `If-None-Match` names the recording's ETag. No body; the blob is not read and the download bucket is not charged.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=31536000, immutable`.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The recording's ETag, as on the 200.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "No public recording: every id the public fruit route answers 404 for, a hash that is not the fruit's stored recording, and a recording whose stored bytes are missing, corrupt or not a plain WAV. Every such URL gets this same body and headers; nothing is echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: fruits",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "416": {
            "description": "Range not satisfiable: one well-formed byte range that selects no byte of the recording (its first position is at or past the end, or a zero-length suffix). Nothing is read and the download bucket is not charged.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Content-Range": {
                "description": "`bytes */<size>`: the recording's size in bytes.",
                "schema": {
                  "type": "string"
                }
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "range not satisfiable",
                  "code": "range_not_satisfiable"
                }
              }
            }
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds. Also when this client's download bucket (shared with the EPCIS download; one token per started KiB served, the whole recording or the one byte range a 206 answers: bursts of 32 MiB, then 64 KiB a second) does not hold the bytes to serve; that bucket is taken after the visibility lookups and before the blob is read, and a 304 never takes from it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/maps/{style}/{tileset}/{communes}/{osm_id}.svg": {
      "get": {
        "operationId": "getPublicCommuneMap",
        "summary": "Public commune map image of a record's growing area",
        "description": "#293: the image a public lot or fruit record's `map.url` names (PublicCommuneMap): an SVG of 448 x 252 pixels showing one commune's OpenStreetMap boundary on raster map tiles CropPath renders itself from an OpenStreetMap extract (zooms 5 to 13). Nothing is fetched from another site, neither by the server nor by the browser: the tiles are embedded in the image as `data:` PNG images. The image holds only rectangles, embedded images, the outline path and the attribution text \"© OpenMapTiles © OpenStreetMap contributors\": no script, no external reference. Its first path part names the drawing's version (the current style version: `s` followed by a number, for example `s2`) and the other three immutable data (a tile dataset, a commune dataset and an OpenStreetMap relation), so its bytes never change: it is cached for a year, with the SHA-256 of the body as its ETag. A change to how the map is drawn takes a new version, so it always comes with a new URL; the URL of an earlier version answers 301 to the current one. Any visitor may ask for any commune: the image is public OpenStreetMap data and names no growing area. Anonymous and tenant-less (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Not part of the partner SDK clients (`x-not-in-sdk`): an image the public pages load.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "style",
            "in": "path",
            "required": true,
            "description": "The drawing's version, `s` followed by a number (for example `s2`): the current style version answers the image, an earlier one 301 to the current URL, any other 404.",
            "schema": {
              "type": "string",
              "pattern": "^s[1-9][0-9]{0,3}$"
            },
            "example": "s2"
          },
          {
            "name": "tileset",
            "in": "path",
            "required": true,
            "description": "The tile dataset's key, `osmtiles-<extract timestamp>`.",
            "schema": {
              "type": "string"
            },
            "example": "osmtiles-2026-10-16T20:21:21Z"
          },
          {
            "name": "communes",
            "in": "path",
            "required": true,
            "description": "The commune dataset's key, `osm-<extract timestamp>`.",
            "schema": {
              "type": "string"
            },
            "example": "osm-2026-10-15T20:21:00Z"
          },
          {
            "name": "osm_id",
            "in": "path",
            "required": true,
            "description": "The commune's OpenStreetMap relation id, digits without a leading zero.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,11}$"
            },
            "example": "19305426"
          }
        ],
        "responses": {
          "200": {
            "description": "The commune map.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=31536000, immutable`. Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The SHA-256 of the body, quoted.",
                "schema": {
                  "type": "string"
                }
              },
              "X-Content-Type-Options": {
                "description": "`nosniff`.",
                "schema": {
                  "type": "string"
                }
              },
              "Content-Security-Policy": {
                "description": "`default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox`: inert when the image is opened on its own.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "image/svg+xml": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "image/svg+xml"
                },
                "example": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 448 252\" width=\"448\" height=\"252\">...</svg>"
              }
            }
          },
          "301": {
            "description": "The URL of an earlier drawing version: the map is at `Location`, its current URL. No body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Location": {
                "description": "The map's current same-origin path, `/v1/public/maps/{style}/{tileset}/{communes}/{osm_id}.svg`, `{style}` the current style version (`s` followed by a number, for example `s2`).",
                "schema": {
                  "type": "string"
                }
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300`, as a public record: never `immutable`, so a later version is followed at once.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "304": {
            "description": "Not modified: the request's `If-None-Match` names the image's ETag. No body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=31536000, immutable`.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The image's ETag, as on the 200.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "No such map: a drawing version that is not one (malformed, or later than the current), a tile dataset or a commune dataset that is not imported, a relation that is not a commune of that dataset, or a malformed part. Every such URL gets this same body and headers; nothing is echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale).",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: maps",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds. Also when this client's download bucket (shared with the EPCIS download; one token per started KiB served, the whole recording or the one byte range a 206 answers: bursts of 32 MiB, then 64 KiB a second) does not hold the bytes to serve; that bucket is taken after the visibility lookups and before the blob is read, and a 304 never takes from it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/public/maps/{tileset}/{communes}/{osm_id}.svg": {
      "get": {
        "operationId": "getPublicCommuneMapUnversioned",
        "summary": "Public commune map image, the path before its drawing version (moved)",
        "description": "#293: the map URL as first published, without the drawing version (getPublicCommuneMap). Its images were drawn in the first style and cached for a year as immutable, so the current drawing is never served under it: a URL that names a stored map answers 301 to its current URL (`/v1/public/maps/{style}/{tileset}/{communes}/{osm_id}.svg`, `{style}` the current style version: `s` followed by a number, for example `s2`), cached as briefly as a public record. Anonymous and tenant-less (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Not part of the partner SDK clients (`x-not-in-sdk`): an image the public pages load.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "tileset",
            "in": "path",
            "required": true,
            "description": "The tile dataset's key, `osmtiles-<extract timestamp>`.",
            "schema": {
              "type": "string"
            },
            "example": "osmtiles-2026-10-16T20:21:21Z"
          },
          {
            "name": "communes",
            "in": "path",
            "required": true,
            "description": "The commune dataset's key, `osm-<extract timestamp>`.",
            "schema": {
              "type": "string"
            },
            "example": "osm-2026-10-15T20:21:00Z"
          },
          {
            "name": "osm_id",
            "in": "path",
            "required": true,
            "description": "The commune's OpenStreetMap relation id, digits without a leading zero.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,11}$"
            },
            "example": "19305426"
          }
        ],
        "responses": {
          "301": {
            "description": "A stored map: it is at `Location`, its current URL. No body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Location": {
                "description": "The map's current same-origin path, `/v1/public/maps/{style}/{tileset}/{communes}/{osm_id}.svg`, `{style}` the current style version (`s` followed by a number, for example `s2`).",
                "schema": {
                  "type": "string"
                }
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300`, as a public record: never `immutable`, so a later version is followed at once.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "No such map: a tile dataset or a commune dataset that is not imported, a relation that is not a commune of that dataset, or a malformed part. Every such URL gets this same body and headers; nothing is echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale).",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: maps",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds. Also when this client's download bucket (shared with the EPCIS download; one token per started KiB served, the whole recording or the one byte range a 206 answers: bursts of 32 MiB, then 64 KiB a second) does not hold the bytes to serve; that bucket is taken after the visibility lookups and before the blob is read, and a 304 never takes from it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/public/lots/{publicId}/fruits": {
      "get": {
        "operationId": "listPublicLotFruits",
        "summary": "Per-fruit results of a public lot",
        "description": "U5 (#58, man2 \"Xem kết quả từng quả và bản ghi âm gốc\"): one page of a public lot's fruits, in fruit order, from an explicit allowlist (PublicLotFruit): code, public id, effective ripeness level, model confidence, weight, grade, read-time tier, sensory-override flag and the URL of the original recording. A fruit is listed under exactly the public fruit record's rule (getPublicFruit: recorded or overridden, a bound signed knock, every non-null measurement field, a lot with a growing area); a public lot without a growing area lists none. `group=measured` (default) lists the fruits whose level is the device's; `group=overridden` lists those an operator overrode, kept at Self-declared and shown separately (man2). Anonymous and tenant-less like the public lot record (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the public lot's lookup and context (a fixed number of statements), one count and one page statement (at most 201 rows, keyset on the lot's fruit numbers).",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          },
          {
            "name": "group",
            "in": "query",
            "required": false,
            "description": "`measured` (default): levels from the device; `overridden`: levels an operator replaced (Self-declared).",
            "schema": {
              "type": "string",
              "enum": [
                "measured",
                "overridden"
              ],
              "default": "measured"
            },
            "example": "measured"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of the same group.",
            "schema": {
              "type": "string"
            },
            "example": "eyJuIjoyfQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 100
            },
            "example": 100
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the group.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicLotFruitPage"
                },
                "example": {
                  "lot": {
                    "public_id": "074eb09b371fc71c380da235aea9c14a",
                    "code": "LO-260928-014"
                  },
                  "group": "measured",
                  "total": 120,
                  "items": [
                    {
                      "public_id": "5c1f0e2a9b7d4c3e8f6a1b2c3d4e5f60",
                      "code": "Q-014-0001",
                      "ripeness_level": 3,
                      "model_confidence": 0.91,
                      "weight_kg": 2.84,
                      "grade": "A",
                      "tier": "device_recorded",
                      "sensory_override": false,
                      "recording_url": "/v1/public/fruits/5c1f0e2a9b7d4c3e8f6a1b2c3d4e5f60/recordings/9f2c0d5ab1e7c3f4a6b8d0e2f4a6c8e0b2d4f6a8c0e2a4c6e8a0c2e4a6c8e0b2"
                    },
                    {
                      "public_id": "6d2a1f3b0c8e5d4f9a7b2c3d4e5f6a71",
                      "code": "Q-014-0002",
                      "ripeness_level": 2,
                      "model_confidence": 0.88,
                      "weight_kg": 2.94,
                      "grade": "A",
                      "tier": "device_recorded",
                      "sensory_override": false,
                      "recording_url": null
                    }
                  ],
                  "next_cursor": "eyJuIjoyfQ"
                }
              }
            }
          },
          "400": {
            "description": "`group`, `limit` or `cursor` is not one this route accepts (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "group": {
                    "value": {
                      "error": "bad group",
                      "code": "bad_group"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Not a public lot: every id the public lot route answers 404 for gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/recall": {
      "post": {
        "operationId": "recallLot",
        "summary": "Recall or withdraw a lot (terminal)",
        "description": "Recalls (`recalled`) or withdraws (`withdrawn`) the whole lot (P5, #41; domain model, State Machines: exceptional terminal public states). In one transaction under the lot's lock: its open or paused measurement sessions close, its status changes, the recall is stored with the state the lot left and the trace counts, an outbound notice is stored for the outbound adapter (#90, `pending`: nothing is sent), the lot's trust seal is taken when it had none, and the audit row is written (`lot.recall`: the prior and new status, kind, reason, scope and counts; never the note). Nothing is deleted: the lot keeps its history and stays public when it was. The public lot and fruit records then show status `recalled` or `withdrawn` from the recall time with `status_reason`, and a displayed tier of Self-declared for good (reason `lot_recalled`). Packing and shipping refuse the lot, and a shipment carrying it cannot depart. There is no reversal: a second recall or withdrawal is refused with 409. Allowed for tenant_admin and platform_admin acting for the tenant; another tenant's lot answers like a missing one. Step-up (#87): a signed-in session of an account with two-step sign-in must have confirmed a code from its authenticator app (or a backup code) within the last 5 minutes and its password within the last 10 minutes, else 401 `mfa_step_up_required` before anything is done (no audit row): confirm both with POST /v1/auth/reauth, then repeat the request. A session of an account without two-step sign-in, API tokens and API clients are served as before.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_recall"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LotRecallRequest"
              },
              "example": {
                "kind": "recall",
                "reason": "contamination",
                "scope": "consumer",
                "note": "Cadmium over the CN limit in the lab's re-test."
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The lot's trace with its recall.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotTrace"
                },
                "example": {
                  "lot": {
                    "code": "LO-260928-014",
                    "status": "recalled",
                    "product": "durian",
                    "variety": "Ri6",
                    "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
                  },
                  "recall": {
                    "kind": "recall",
                    "status": "recalled",
                    "reason": "contamination",
                    "scope": "consumer",
                    "note": "Cadmium over the CN limit in the lab's re-test.",
                    "prior_status": "shipped",
                    "recalled_by": "user-7",
                    "recalled_at": 1790010000.0,
                    "cartons": 2,
                    "shipments": 1,
                    "notice": {
                      "target": "national_portal",
                      "status": "pending",
                      "attempts": 0,
                      "created_at": 1790010000.0,
                      "delivered_at": null
                    }
                  },
                  "backward": {
                    "facility": {
                      "code": "VN-TGPH-021",
                      "name": "Tân Phú"
                    },
                    "growing_area": {
                      "code": "VN-TGOR-0387",
                      "commune": "Ngũ Hiệp",
                      "district": "Cai Lậy",
                      "province": "Tiền Giang"
                    },
                    "harvest": {
                      "date": "2026-09-27",
                      "at": 1790470000.0,
                      "kg": 500.0,
                      "source": "signed_event"
                    }
                  },
                  "forward": {
                    "cartons": {
                      "count": 2,
                      "fruits": 5,
                      "net_mass_kg": 14.37,
                      "truncated": false,
                      "items": [
                        {
                          "code": "C-0928014-0001",
                          "carton_no": 1,
                          "fruits": 3,
                          "net_mass_kg": 8.6,
                          "shipment": "SH-260930-01"
                        },
                        {
                          "code": "C-0928014-0002",
                          "carton_no": 2,
                          "fruits": 2,
                          "net_mass_kg": 5.77,
                          "shipment": "SH-260930-01"
                        }
                      ]
                    },
                    "shipment": {
                      "code": "SH-260930-01",
                      "facility": "VN-TGPH-021",
                      "status": "departed",
                      "container": "CSQU3054383",
                      "destination": "CN",
                      "border_gate": "Hữu Nghị",
                      "departed_at": 1790722800.0,
                      "cartons": 2
                    }
                  },
                  "related_lots": {
                    "items": [
                      {
                        "code": "LO-260928-015",
                        "status": "packed",
                        "harvest_date": "2026-09-27"
                      }
                    ],
                    "truncated": false
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a kind, reason or scope outside the enums, a note over 1,000 characters, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: by",
                      "code": "unknown_fields"
                    }
                  },
                  "kind": {
                    "value": {
                      "error": "invalid kind: recall or withdrawal",
                      "code": "invalid_kind"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: one of contamination, pathogen, foreign_matter, labelling, quality, regulatory, traceability, other",
                      "code": "invalid_reason"
                    }
                  },
                  "scope": {
                    "value": {
                      "error": "invalid scope: one of consumer, retail, wholesale",
                      "code": "invalid_scope"
                    }
                  },
                  "note": {
                    "value": {
                      "error": "invalid note: a string of at most 1000 characters",
                      "code": "invalid_note"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            },
            "x-sdk-description": "No valid session, API token or legacy token."
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot is already recalled or withdrawn (both are terminal). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "terminal": {
                    "value": {
                      "error": "lot is terminal: recalled",
                      "code": "lot_is_terminal"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Recalls (`recalled`) or withdraws (`withdrawn`) the whole lot (P5, #41; domain model, State Machines: exceptional terminal public states). In one transaction under the lot's lock: its open or paused measurement sessions close, its status changes, the recall is stored with the state the lot left and the trace counts, an outbound notice is stored for the outbound adapter (#90, `pending`: nothing is sent), the lot's trust seal is taken when it had none, and the audit row is written (`lot.recall`: the prior and new status, kind, reason, scope and counts; never the note). Nothing is deleted: the lot keeps its history and stays public when it was. The public lot and fruit records then show status `recalled` or `withdrawn` from the recall time with `status_reason`, and a displayed tier of Self-declared for good (reason `lot_recalled`). Packing and shipping refuse the lot, and a shipment carrying it cannot depart. There is no reversal: a second recall or withdrawal is refused with 409. Allowed for tenant_admin and platform_admin acting for the tenant; another tenant's lot answers like a missing one."
      }
    },
    "/v1/lots/{lot}/trace": {
      "get": {
        "operationId": "getLotTrace",
        "summary": "Trace a lot forward and back (the affected set of a recall)",
        "description": "The lot's affected set (P5, #41; see LotTrace), whether or not it is recalled: a read with a fixed number of statements, not audited, never cached (`Cache-Control: no-store`). Allowed for tenant_admin, platform_admin acting for the tenant and auditor (staff only); operators and labs are refused; another tenant's lot answers like a missing one. With `merges=1` the trace also names the lots its chain of lot merges links (#259): the lots the chain produced from this one (`forward.merged_into`), the input lots of the merge that produced this one (`backward.merged_from`) and the lot of each listed carton (`forward.cartons.items[].lot`); without it those fields are absent and the trace reads as before. The parameter and the fields are not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.3.0 was released before them, and its clients refuse a field they do not know.",
        "x-sdk-description": "The lot's affected set (P5, #41; see LotTrace), whether or not it is recalled: a read with a fixed number of statements, not audited, never cached (`Cache-Control: no-store`). Allowed for tenant_admin, platform_admin acting for the tenant and auditor (staff only); operators and labs are refused; another tenant's lot answers like a missing one.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "recall_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "merges",
            "in": "query",
            "required": false,
            "description": "`1` adds the lots the chain of merges links (`forward.merged_into`, `backward.merged_from`, `forward.cartons.items[].lot`); `0` or none leaves them out; any other value is refused (400 `bad merges`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's trace.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotTrace"
                },
                "example": {
                  "lot": {
                    "code": "LO-260928-014",
                    "status": "recalled",
                    "product": "durian",
                    "variety": "Ri6",
                    "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
                  },
                  "recall": {
                    "kind": "recall",
                    "status": "recalled",
                    "reason": "contamination",
                    "scope": "consumer",
                    "note": "Cadmium over the CN limit in the lab's re-test.",
                    "prior_status": "shipped",
                    "recalled_by": "user-7",
                    "recalled_at": 1790010000.0,
                    "cartons": 2,
                    "shipments": 1,
                    "notice": {
                      "target": "national_portal",
                      "status": "pending",
                      "attempts": 0,
                      "created_at": 1790010000.0,
                      "delivered_at": null
                    }
                  },
                  "backward": {
                    "facility": {
                      "code": "VN-TGPH-021",
                      "name": "Tân Phú"
                    },
                    "growing_area": {
                      "code": "VN-TGOR-0387",
                      "commune": "Ngũ Hiệp",
                      "district": "Cai Lậy",
                      "province": "Tiền Giang"
                    },
                    "harvest": {
                      "date": "2026-09-27",
                      "at": 1790470000.0,
                      "kg": 500.0,
                      "source": "signed_event"
                    }
                  },
                  "forward": {
                    "cartons": {
                      "count": 2,
                      "fruits": 5,
                      "net_mass_kg": 14.37,
                      "truncated": false,
                      "items": [
                        {
                          "code": "C-0928014-0001",
                          "carton_no": 1,
                          "fruits": 3,
                          "net_mass_kg": 8.6,
                          "shipment": "SH-260930-01"
                        },
                        {
                          "code": "C-0928014-0002",
                          "carton_no": 2,
                          "fruits": 2,
                          "net_mass_kg": 5.77,
                          "shipment": "SH-260930-01"
                        }
                      ]
                    },
                    "shipment": {
                      "code": "SH-260930-01",
                      "facility": "VN-TGPH-021",
                      "status": "departed",
                      "container": "CSQU3054383",
                      "destination": "CN",
                      "border_gate": "Hữu Nghị",
                      "departed_at": 1790722800.0,
                      "cartons": 2
                    }
                  },
                  "related_lots": {
                    "items": [
                      {
                        "code": "LO-260928-015",
                        "status": "packed",
                        "harvest_date": "2026-09-27"
                      }
                    ],
                    "truncated": false
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/recall-export.csv": {
      "get": {
        "operationId": "getLotRecallExportCsv",
        "summary": "FSMA-204-style export of a lot's affected records (CSV)",
        "description": "The sortable record of the lot's critical tracking events (P5, #41; RecallExport describes the rows and columns), with the recall kind and reason on every row (empty while the lot is not recalled), so a records request is answered within FSMA 204's 24 hours by one request. Complete and bounded for every lot (at most 9,999 cartons). An audited read (`export.recall`: the format and the row count), downloaded as an attachment (`Content-Disposition`), never cached. Allowed for tenant_admin, platform_admin acting for the tenant and auditor; operators and labs are refused; another tenant's lot answers like a missing one.",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "recall_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "CSV with a header row (CRLF line ends); a cell starting with =, +, -, @, a tab or a carriage return gets a leading ' so a spreadsheet never runs it as a formula.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "traceability_lot_code,critical_tracking_event,event_date,event_time,location,location_description,product_description,quantity,unit_of_measure,carton,fruit_count,shipment,container,destination,border_gate,recall_kind,recall_reason\r\nLO-260928-014,harvesting,2026-09-27,06:40:00+07:00,VN-TGOR-0387,Ngũ Hiệp, Cai Lậy, Tiền Giang,durian Ri6,500.0,kg,,,,,,,recall,contamination\r\n"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/recall-export.json": {
      "get": {
        "operationId": "getLotRecallExportJson",
        "summary": "FSMA-204-style export of a lot's affected records (JSON)",
        "description": "The sortable record of the lot's critical tracking events (P5, #41; RecallExport describes the rows and columns), with the recall kind and reason on every row (empty while the lot is not recalled), so a records request is answered within FSMA 204's 24 hours by one request. Complete and bounded for every lot (at most 9,999 cartons). An audited read (`export.recall`: the format and the row count), downloaded as an attachment (`Content-Disposition`), never cached. Allowed for tenant_admin, platform_admin acting for the tenant and auditor; operators and labs are refused; another tenant's lot answers like a missing one.",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "recall_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The export document (RecallExport).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecallExport"
                },
                "example": {
                  "format": "agritrace-recall-export/1",
                  "lot": "LO-260928-014",
                  "generated_at": "2026-10-02T09:00:00+07:00",
                  "recall": {
                    "kind": "recall",
                    "reason": "contamination",
                    "scope": "consumer",
                    "recalled_at": "2026-10-01T15:20:00+07:00"
                  },
                  "columns": [
                    "traceability_lot_code",
                    "critical_tracking_event",
                    "event_date",
                    "event_time",
                    "location",
                    "location_description",
                    "product_description",
                    "quantity",
                    "unit_of_measure",
                    "carton",
                    "fruit_count",
                    "shipment",
                    "container",
                    "destination",
                    "border_gate",
                    "recall_kind",
                    "recall_reason"
                  ],
                  "rows": [
                    {
                      "traceability_lot_code": "LO-260928-014",
                      "critical_tracking_event": "harvesting",
                      "event_date": "2026-09-27",
                      "event_time": "06:40:00+07:00",
                      "location": "VN-TGOR-0387",
                      "location_description": "Ngũ Hiệp, Cai Lậy, Tiền Giang",
                      "product_description": "durian Ri6",
                      "quantity": 500.0,
                      "unit_of_measure": "kg",
                      "carton": "",
                      "fruit_count": "",
                      "shipment": "",
                      "container": "",
                      "destination": "",
                      "border_gate": "",
                      "recall_kind": "recall",
                      "recall_reason": "contamination"
                    },
                    {
                      "traceability_lot_code": "LO-260928-014",
                      "critical_tracking_event": "initial_packing",
                      "event_date": "2026-09-29",
                      "event_time": "07:30:00+07:00",
                      "location": "VN-TGPH-021",
                      "location_description": "Tân Phú",
                      "product_description": "durian Ri6",
                      "quantity": 8.6,
                      "unit_of_measure": "kg",
                      "carton": "C-0928014-0001",
                      "fruit_count": 3,
                      "shipment": "",
                      "container": "",
                      "destination": "",
                      "border_gate": "",
                      "recall_kind": "recall",
                      "recall_reason": "contamination"
                    },
                    {
                      "traceability_lot_code": "LO-260928-014",
                      "critical_tracking_event": "shipping",
                      "event_date": "2026-09-30",
                      "event_time": "06:00:00+07:00",
                      "location": "VN-TGPH-021",
                      "location_description": "Tân Phú",
                      "product_description": "durian Ri6",
                      "quantity": 8.6,
                      "unit_of_measure": "kg",
                      "carton": "C-0928014-0001",
                      "fruit_count": 3,
                      "shipment": "SH-260930-01",
                      "container": "CSQU3054383",
                      "destination": "CN",
                      "border_gate": "Hữu Nghị",
                      "recall_kind": "recall",
                      "recall_reason": "contamination"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/recalls": {
      "get": {
        "operationId": "listRecalls",
        "summary": "The company's recalls and withdrawals",
        "description": "#322: the company's lot recalls and withdrawals, newest first (at most 100), each with its lot code, the recall (LotRecall: kind, reason category, scope, staff note, the state the lot left, the opaque operator id, the time, the cartons and shipments the trace found) and its outbound notice for the national portal, stored and not sent yet (`pending`) until the outbound adapter delivers it; `total` counts every recall and withdrawal of the company and `notices_pending` their notices not sent yet. Never cached (`Cache-Control: no-store`). Allowed for tenant_admin, platform_admin acting for the tenant and auditor (staff only); operators and labs are refused. Not audited (a read). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "recall_read"
            ]
          }
        ],
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The company's recalls and withdrawals.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecallList"
                },
                "example": {
                  "items": [
                    {
                      "lot": "LO-260928-014",
                      "recall": {
                        "kind": "recall",
                        "status": "recalled",
                        "reason": "contamination",
                        "scope": "consumer",
                        "note": "",
                        "prior_status": "shipped",
                        "recalled_by": "user-12",
                        "recalled_at": 1790700000.0,
                        "cartons": 41,
                        "shipments": 1,
                        "notice": {
                          "target": "national_portal",
                          "status": "pending",
                          "attempts": 0,
                          "created_at": 1790700000.0,
                          "delivered_at": null
                        }
                      }
                    }
                  ],
                  "total": 1,
                  "notices_pending": 1
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/api-tokens": {
      "get": {
        "operationId": "listApiTokens",
        "summary": "The tenant's API tokens",
        "description": "Newest first, one page (`limit`, default 50, at most 200; `cursor` from the previous page), every status. Never returns a token or its hash. Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session only. Not audited (a read). `no-store`.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of tokens.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApiTokenPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 7,
                      "name": "erp-sync",
                      "role": "operator",
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5,
                      "last_used_at": null,
                      "expires_at": 1797776000.5,
                      "revoked_at": null,
                      "revoke_reason": null,
                      "revoked_by": null,
                      "status": "active"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token or the legacy token is refused), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createApiToken",
        "summary": "Create an API token (shown once)",
        "description": "Creates a token of the caller's tenant and returns it once, in `secret` (`no-store`); only its SHA-256 is stored, so no later read returns it. A tenant holds at most 100 live tokens. Audited (`api_token.create`, in the same transaction: the token id, name, role and expiry, never the token). Allowed for tenant_admin and platform_admin acting for the tenant, through a session only. A session must have confirmed its password within the last 10 minutes (SELF-1-2, #183), else 401 `reauthentication_required` before anything is done.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApiTokenCreate"
              },
              "example": {
                "name": "erp-sync",
                "role": "operator",
                "expires_in_days": 90
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The token, with the secret shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApiTokenCreated"
                },
                "example": {
                  "token": {
                    "id": 7,
                    "name": "erp-sync",
                    "role": "operator",
                    "created_by": "admin@coop.example",
                    "created_at": 1790000000.5,
                    "last_used_at": null,
                    "expires_at": 1797776000.5,
                    "revoked_at": null,
                    "revoke_reason": null,
                    "revoked_by": null,
                    "status": "active"
                  },
                  "secret": "agt_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGx"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad name, role or expiry, or a bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the token secret, which is never stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "name": {
                    "value": {
                      "error": "invalid name: a letter or digit, then up to 63 letters, digits, '.', '_' or '-'",
                      "code": "invalid_name"
                    }
                  },
                  "role": {
                    "value": {
                      "error": "invalid role: one of tenant_admin, operator, auditor",
                      "code": "invalid_role"
                    }
                  },
                  "expiry": {
                    "value": {
                      "error": "invalid expires_in_days: a whole number of days from 1 to 3650, or null",
                      "code": "invalid_expires_in_days"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: tenant",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The tenant already holds 100 live tokens: revoke one first.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "token limit reached: at most 100 live tokens per tenant",
                  "code": "token_limit_reached"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/api-tokens/{id}/revoke": {
      "post": {
        "operationId": "revokeApiToken",
        "summary": "Revoke an API token",
        "description": "Revokes one of the tenant's tokens with a reason; it stops authenticating at once. A revoked token stays listed (no DELETE). Audited (`api_token.revoke`, in the same transaction, with the reason). Allowed for tenant_admin and platform_admin acting for the tenant, through a session only; another tenant's token answers like a missing one.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The token id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApiTokenRevoke"
              },
              "example": {
                "reason": "leaked in a CI log"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The token, revoked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApiToken"
                },
                "example": {
                  "id": 7,
                  "name": "erp-sync",
                  "role": "operator",
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "last_used_at": null,
                  "expires_at": 1797776000.5,
                  "revoked_at": 1790003600.5,
                  "revoke_reason": "leaked in a CI log",
                  "revoked_by": "admin@coop.example",
                  "status": "revoked"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a missing, blank, multi-line or longer than 200 characters reason, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: 1 to 200 characters on one line",
                      "code": "invalid_reason"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: role",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such token of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The token is already revoked. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "token_already_revoked": {
                    "value": {
                      "error": "token already revoked",
                      "code": "token_already_revoked"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/oauth/token": {
      "post": {
        "operationId": "oauthToken",
        "summary": "Get an access token (OAuth2 client credentials)",
        "description": "RFC 6749 §4.4 client credentials grant. The client authenticates with HTTP Basic (`client_id:client_secret`, each form-urlencoded) or with `client_id` and `client_secret` in the body, never both. The response carries a bearer access token (`ago_...`) valid for 900 seconds with the client's scopes, or the subset asked for in `scope` (space separated); send it as `Authorization: Bearer <access_token>`. A token reaches only the routes whose permission is among its scopes, within the client's tenant and, for an operator client, its facilities. A client holds at most 20 live tokens (429 above it); ask for a new token when one expires rather than one per request. Errors are RFC 6749 §5.2 bodies (`error`, `error_description`) that also carry the API's `code`. Audited (`oauth.token`, in the same transaction: the client, the scopes granted and the expiry, never the token; a refused request writes `oauth.token.failed`). Rate limited per client address. An `Idempotency-Key` header is refused (400 `idempotency_key_not_supported`): the response would hold a secret. #205: an expired client, and a client called from a source address outside its allowed networks (the address the API sees: `CF-Connecting-IP` from a trusted proxy, else the connection's), is refused `invalid_client` exactly like a wrong secret; a token of such a client then answers 401 `missing_or_invalid_token` on every call.",
        "tags": [
          "auth"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/x-www-form-urlencoded": {
              "schema": {
                "$ref": "#/components/schemas/OAuthTokenRequest"
              },
              "example": {
                "grant_type": "client_credentials",
                "scope": "lot_read"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The access token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthToken"
                },
                "example": {
                  "access_token": "ago_VGhpcyBpcyBhbiBleGFtcGxlIGFjY2VzcyB0b2tlbiE",
                  "token_type": "Bearer",
                  "expires_in": 900,
                  "scope": "lot_read lot_write"
                }
              }
            }
          },
          "400": {
            "description": "RFC 6749 §5.2: `invalid_request` (not a form body, a parameter given twice, no `grant_type`, two authentication methods), `unsupported_grant_type` (anything but client_credentials) or `invalid_scope` (a malformed scope or one the client was not granted); or a bad X-Request-Id; or an `Idempotency-Key` header (`idempotency_key_not_supported`, the API's usual body).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "examples": {
                  "invalid_request": {
                    "value": {
                      "error": "invalid_request",
                      "error_description": "grant_type is required",
                      "code": "invalid_request"
                    }
                  },
                  "unsupported_grant_type": {
                    "value": {
                      "error": "unsupported_grant_type",
                      "error_description": "only client_credentials is supported",
                      "code": "unsupported_grant_type"
                    }
                  },
                  "invalid_scope": {
                    "value": {
                      "error": "invalid_scope",
                      "error_description": "scope: a permission the client was not granted",
                      "code": "invalid_scope"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Client authentication failed (RFC 6749 §5.2 `invalid_client`): no credentials, a malformed Basic header, an unknown or revoked client or a wrong secret, all answered the same.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              },
              "WWW-Authenticate": {
                "description": "`Basic realm=\"agritrace\"`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "example": {
                  "error": "invalid_client",
                  "error_description": "client authentication failed",
                  "code": "invalid_client"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many requests from this client address (see the 429 of the bucket, `too_many_requests`), or the client already holds 20 live tokens (`invalid_request`, `Retry-After` until its oldest expires).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "examples": {
                  "throttled": {
                    "value": {
                      "error": "too many requests",
                      "code": "too_many_requests"
                    }
                  },
                  "live_tokens": {
                    "value": {
                      "error": "invalid_request",
                      "error_description": "too many live tokens: at most 20 per client",
                      "code": "invalid_request"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "RFC 6749 §4.4 client credentials grant. The client authenticates with HTTP Basic (`client_id:client_secret`, each form-urlencoded) or with `client_id` and `client_secret` in the body, never both. The response carries a bearer access token (`ago_...`) valid for 900 seconds with the client's scopes, or the subset asked for in `scope` (space separated); send it as `Authorization: Bearer <access_token>`. A token reaches only the routes whose permission is among its scopes, within the client's tenant and, for an operator client, its facilities. A client holds at most 20 live tokens (429 above it); ask for a new token when one expires rather than one per request. Errors are RFC 6749 §5.2 bodies (`error`, `error_description`) that also carry the API's `code`. Audited (`oauth.token`, in the same transaction: the client, the scopes granted and the expiry, never the token; a refused request writes `oauth.token.failed`). Rate limited per client address. An `Idempotency-Key` header is refused (400 `idempotency_key_not_supported`): the response would hold a secret."
      }
    },
    "/v1/oauth/revoke": {
      "post": {
        "operationId": "oauthRevoke",
        "summary": "Revoke an access token (RFC 7009)",
        "description": "The client that holds an access token revokes it; it stops authenticating at once. Client authentication as for the token endpoint. 200 whether or not `token` was a live token of this client: an unknown, expired or another client's token is left alone and answered the same (`token_type_hint` is accepted and ignored). Audited (`oauth.revoke`: the client and whether a token was revoked, never the token). Rate limited with the token endpoint. An `Idempotency-Key` header is refused (400 `idempotency_key_not_supported`): revocation is idempotent by itself.",
        "tags": [
          "auth"
        ],
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/x-www-form-urlencoded": {
              "schema": {
                "$ref": "#/components/schemas/OAuthRevokeRequest"
              },
              "example": {
                "token": "ago_VGhpcyBpcyBhbiBleGFtcGxlIGFjY2VzcyB0b2tlbiE",
                "token_type_hint": "access_token"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Done (or nothing to do).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": false,
                  "properties": {}
                },
                "example": {}
              }
            }
          },
          "400": {
            "description": "RFC 6749 §5.2 `invalid_request`: not a form body, a parameter given twice, no `token`, two authentication methods; or a bad X-Request-Id; or an `Idempotency-Key` header (`idempotency_key_not_supported`, the API's usual body).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "examples": {
                  "invalid_request": {
                    "value": {
                      "error": "invalid_request",
                      "error_description": "token is required",
                      "code": "invalid_request"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Client authentication failed (RFC 6749 §5.2 `invalid_client`): no credentials, a malformed Basic header, an unknown or revoked client or a wrong secret, all answered the same.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              },
              "WWW-Authenticate": {
                "description": "`Basic realm=\"agritrace\"`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "example": {
                  "error": "invalid_client",
                  "error_description": "client authentication failed",
                  "code": "invalid_client"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many requests to the OAuth2 endpoints from this client address (one per-IP token bucket for the token and revocation endpoints: bursts of 30, then 30 a minute). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store` (RFC 6749 §5.1).",
                "schema": {
                  "type": "string"
                }
              },
              "Pragma": {
                "description": "`no-cache`.",
                "schema": {
                  "type": "string"
                }
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthError"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/oauth-clients": {
      "get": {
        "operationId": "listOAuthClients",
        "summary": "The tenant's OAuth2 API clients",
        "description": "Newest first, one page (`limit`, default 50, at most 200; `cursor` from the previous page), every status. Never returns a secret or its hash. Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session only. Not audited (a read). `no-store`.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of clients.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthClientPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
                      "name": "erp-sync",
                      "role": "operator",
                      "scopes": [
                        "lot_read",
                        "lot_write"
                      ],
                      "facilities": [
                        "VN-TGPH-021"
                      ],
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5,
                      "last_token_at": null,
                      "revoked_at": null,
                      "revoke_reason": null,
                      "revoked_by": null,
                      "status": "active"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an OAuth2 access token or the legacy token is refused), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createOAuthClient",
        "summary": "Register an OAuth2 API client (secret shown once)",
        "description": "Registers an API client of the caller's tenant and returns its secret once, in `client_secret` (`no-store`); only its SHA-256 is stored, so no later read returns it. `scopes` are permissions (the names of the API's route policies) the client's role can hold; `facilities` limits an operator client to some of the tenant's facilities. A tenant holds at most 50 live clients. Audited (`oauth_client.create`, in the same transaction: the client id, name, role, scopes and facilities, never the secret). Allowed for tenant_admin and platform_admin acting for the tenant, through a session only. An `Idempotency-Key` header is refused (400 `idempotency_key_not_supported`): the response would hold a secret. A session must have confirmed its password within the last 10 minutes (SELF-1-2, #183), else 401 `reauthentication_required` before anything is done. #205: the client expires 365 days after it is created (renew it with POST /v1/oauth-clients/{id}/renew), accepts any source address until PUT /v1/oauth-clients/{id}/allowed-ips limits it, and its scopes never change afterwards (a wider client is a new one, which again needs the recent password). The audit row also holds the expiry and `broad_scope` (whether a scope opens a write); GET /v1/oauth-clients/details shows both.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OAuthClientCreate"
              },
              "example": {
                "name": "erp-sync",
                "role": "operator",
                "scopes": [
                  "lot_read",
                  "lot_write"
                ],
                "facilities": [
                  "VN-TGPH-021"
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The client, with its secret shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthClientCreated"
                },
                "example": {
                  "client": {
                    "id": 3,
                    "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
                    "name": "erp-sync",
                    "role": "operator",
                    "scopes": [
                      "lot_read",
                      "lot_write"
                    ],
                    "facilities": [
                      "VN-TGPH-021"
                    ],
                    "created_by": "admin@coop.example",
                    "created_at": 1790000000.5,
                    "last_token_at": null,
                    "revoked_at": null,
                    "revoke_reason": null,
                    "revoked_by": null,
                    "status": "active"
                  },
                  "client_secret": "acs_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGx"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad name or role, scopes the role cannot hold, facilities with a role other than operator or not of the tenant, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "scopes": {
                    "value": {
                      "error": "invalid scopes: not a permission the auditor role can be granted: review",
                      "code": "invalid_scopes"
                    }
                  },
                  "facilities": {
                    "value": {
                      "error": "invalid facilities: not a facility of the tenant",
                      "code": "invalid_facilities"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an OAuth2 access token or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The tenant already holds 50 live clients.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "client limit reached: at most 50 live API clients per tenant",
                  "code": "client_limit_reached"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Registers an API client of the caller's tenant and returns its secret once, in `client_secret` (`no-store`); only its SHA-256 is stored, so no later read returns it. `scopes` are permissions (the names of the API's route policies) the client's role can hold; `facilities` limits an operator client to some of the tenant's facilities. A tenant holds at most 50 live clients. Audited (`oauth_client.create`, in the same transaction: the client id, name, role, scopes and facilities, never the secret). Allowed for tenant_admin and platform_admin acting for the tenant, through a session only. An `Idempotency-Key` header is refused (400 `idempotency_key_not_supported`): the response would hold a secret. A session must have confirmed its password within the last 10 minutes (SELF-1-2, #183), else 401 `reauthentication_required` before anything is done."
      }
    },
    "/v1/oauth-clients/{id}/revoke": {
      "post": {
        "operationId": "revokeOAuthClient",
        "summary": "Revoke an OAuth2 API client",
        "description": "Revokes one of the tenant's API clients with a reason: it gets no new token and every token it holds stops authenticating at once. A revoked client stays listed (no DELETE). Audited (`oauth_client.revoke`, in the same transaction, with the reason). Allowed for tenant_admin and platform_admin acting for the tenant, through a session only; another tenant's client answers like a missing one. #205: its live access tokens are marked revoked in the same transaction (the audit row holds how many, `tokens_revoked`).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The client's row id (`id`).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OAuthClientRevoke"
              },
              "example": {
                "reason": "contract ended"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The client, revoked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthClient"
                },
                "example": {
                  "id": 3,
                  "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
                  "name": "erp-sync",
                  "role": "operator",
                  "scopes": [
                    "lot_read",
                    "lot_write"
                  ],
                  "facilities": [
                    "VN-TGPH-021"
                  ],
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "last_token_at": null,
                  "revoked_at": 1790003600.5,
                  "revoke_reason": "contract ended",
                  "revoked_by": "admin@coop.example",
                  "status": "revoked"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a missing, blank, multi-line or longer than 200 characters reason, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: 1 to 200 characters on one line",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an OAuth2 access token or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such client of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The client is already revoked. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "client_already_revoked": {
                    "value": {
                      "error": "client already revoked",
                      "code": "client_already_revoked"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Revokes one of the tenant's API clients with a reason: it gets no new token and every token it holds stops authenticating at once. A revoked client stays listed (no DELETE). Audited (`oauth_client.revoke`, in the same transaction, with the reason). Allowed for tenant_admin and platform_admin acting for the tenant, through a session only; another tenant's client answers like a missing one."
      }
    },
    "/v1/oauth-clients/details": {
      "get": {
        "operationId": "listOAuthClientDetails",
        "summary": "The tenant's OAuth2 API clients with expiry, sources and last use",
        "description": "#205. Newest first, one page (`limit`, default 50, at most 200; `cursor` from the previous page), every status, like GET /v1/oauth-clients plus each client's expiry (`expires_at`, `expired`), allowed source networks, last use (time, and a keyed hash of the source address, never the address) and write scopes (`broad_scope`). A use is recorded at most once a minute per client and shown within seconds. Never returns a secret or its hash. Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a signed-in session only: an API token, an API client or the legacy token is refused (403). Not audited (a read). `no-store`. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of clients.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthClientDetailPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
                      "name": "erp-sync",
                      "role": "operator",
                      "scopes": [
                        "lot_read",
                        "lot_write"
                      ],
                      "facilities": [
                        "VN-TGPH-021"
                      ],
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5,
                      "last_token_at": 1790003600.5,
                      "revoked_at": null,
                      "revoke_reason": null,
                      "revoked_by": null,
                      "status": "active",
                      "expires_at": 1821536000.5,
                      "expired": false,
                      "allowed_ips": [
                        "203.0.113.0/24"
                      ],
                      "last_used_at": 1790003660.5,
                      "last_used_ip_hash": "5b1f0c3e9a7d2b4c6e8f0a1b3c5d7e9f1a2b4c6d8e0f1a3b5c7d9e1f2a4b6c8d",
                      "write_scopes": [
                        "lot_write"
                      ],
                      "broad_scope": true
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an OAuth2 access token or the legacy token is refused), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/oauth-clients/{id}/renew": {
      "post": {
        "operationId": "renewOAuthClient",
        "summary": "Renew an OAuth2 API client",
        "description": "#205. Sets the client's expiry to `expires_in_days` (1 to 730, default 365) from now, whether or not it has expired; an expired client gets tokens again at once. It may also shorten the lifetime. A revoked client cannot be renewed (409). Audited (`oauth_client.renew`, in the same transaction: the previous and the new expiry). Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a signed-in session only: an API token, an API client or the legacy token is refused (403). Another tenant's client answers like a missing one. A session must have confirmed its password within the last 10 minutes (SELF-1-2, #183), else 401 `reauthentication_required` before anything is done. `no-store`. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The client's row id (`id`).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OAuthClientRenew"
              },
              "example": {
                "expires_in_days": 365
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The client, renewed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthClientDetail"
                },
                "example": {
                  "id": 3,
                  "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
                  "name": "erp-sync",
                  "role": "operator",
                  "scopes": [
                    "lot_read",
                    "lot_write"
                  ],
                  "facilities": [
                    "VN-TGPH-021"
                  ],
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "last_token_at": 1790003600.5,
                  "revoked_at": null,
                  "revoke_reason": null,
                  "revoked_by": null,
                  "status": "active",
                  "expires_at": 1821536000.5,
                  "expired": false,
                  "allowed_ips": [
                    "203.0.113.0/24"
                  ],
                  "last_used_at": 1790003660.5,
                  "last_used_ip_hash": "5b1f0c3e9a7d2b4c6e8f0a1b3c5d7e9f1a2b4c6d8e0f1a3b5c7d9e1f2a4b6c8d",
                  "write_scopes": [
                    "lot_write"
                  ],
                  "broad_scope": true
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, `expires_in_days` not a whole number from 1 to 730, or a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "expires_in_days": {
                    "value": {
                      "error": "invalid expires_in_days: a whole number of days from 1 to 730",
                      "code": "invalid_expires_in_days"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an OAuth2 access token or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such client of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The client is revoked. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "client_revoked": {
                    "value": {
                      "error": "client revoked",
                      "code": "client_revoked"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/oauth-clients/{id}/allowed-ips": {
      "put": {
        "operationId": "setOAuthClientAllowedIps",
        "summary": "Set the source networks an OAuth2 API client may call from",
        "description": "#205. Replaces the client's allowed source networks (`allowed_ips`: 1 to 20 distinct IPv4 or IPv6 networks in CIDR form, normalised; null: any source). The token endpoint, the revocation endpoint and every call made with the client's tokens check the address the API sees (`CF-Connecting-IP` from a trusted proxy, else the connection's; an IPv4-mapped IPv6 address also matches its IPv4 network): from any other source the client gets `invalid_client` and its tokens 401 `missing_or_invalid_token`, like a wrong credential, so a refusal never reveals the list. Its live tokens follow at once. A revoked client is 409. Audited (`oauth_client.allowed_ips`, in the same transaction: whether a list was and is set, how many networks and a keyed hash (an HMAC under the server's hash secret) of each list, never the networks). Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a signed-in session only: an API token, an API client or the legacy token is refused (403). Another tenant's client answers like a missing one. A session must have confirmed its password within the last 10 minutes (SELF-1-2, #183), else 401 `reauthentication_required` before anything is done. `no-store`. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The client's row id (`id`).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OAuthClientAllowedIps"
              },
              "example": {
                "allowed_ips": [
                  "203.0.113.0/24",
                  "2001:db8::/32"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The client with its new allowed sources.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuthClientDetail"
                },
                "example": {
                  "id": 3,
                  "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
                  "name": "erp-sync",
                  "role": "operator",
                  "scopes": [
                    "lot_read",
                    "lot_write"
                  ],
                  "facilities": [
                    "VN-TGPH-021"
                  ],
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "last_token_at": 1790003600.5,
                  "revoked_at": null,
                  "revoke_reason": null,
                  "revoked_by": null,
                  "status": "active",
                  "expires_at": 1821536000.5,
                  "expired": false,
                  "allowed_ips": [
                    "203.0.113.0/24"
                  ],
                  "last_used_at": 1790003660.5,
                  "last_used_ip_hash": "5b1f0c3e9a7d2b4c6e8f0a1b3c5d7e9f1a2b4c6d8e0f1a3b5c7d9e1f2a4b6c8d",
                  "write_scopes": [
                    "lot_write"
                  ],
                  "broad_scope": true
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown or missing field, a value that is not 1 to 20 distinct networks in CIDR form (or null), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "allowed_ips": {
                    "value": {
                      "error": "invalid allowed_ips: 1 to 20 distinct IPv4 or IPv6 networks in CIDR form, or null",
                      "code": "invalid_allowed_ips"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an OAuth2 access token or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such client of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The client is revoked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "client revoked",
                  "code": "client_revoked"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/grading-rules/{variety}/history": {
      "get": {
        "operationId": "getGradingRuleHistory",
        "summary": "The versions of a variety's grading rules",
        "description": "Every version the caller's tenant stored for the variety, newest first, one page (`limit`, default 20, at most 50; `cursor` from the previous page). A variety the tenant has no rules for is a 404 (it is graded with the platform default). Allowed for platform_admin, tenant_admin and auditor; operators and lab are refused. Not audited (a read).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "grading_rule_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "variety",
            "in": "path",
            "required": true,
            "description": "Lot variety (1 to 64 characters), as on the lot.",
            "schema": {
              "type": "string",
              "maxLength": 64
            },
            "example": "Ri6"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 50 (default 20).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50
            },
            "example": 20
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of versions.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GradingRuleHistory"
                },
                "example": {
                  "variety": "Ri6",
                  "items": [
                    {
                      "version": 2,
                      "rules": {
                        "a_levels": [
                          2,
                          3
                        ],
                        "reject_levels": [
                          1,
                          4
                        ],
                        "a_weight_kg": [
                          [
                            2.0,
                            5.0
                          ]
                        ],
                        "a_min_confidence": 0.8,
                        "eating_window": [
                          {
                            "band": "ambient",
                            "end_days": 7,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": "immature"
                          },
                          {
                            "band": "ambient",
                            "end_days": 6,
                            "level": 2,
                            "max_days": 1,
                            "min_days": 0,
                            "start_days": 4,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 4,
                            "level": 2,
                            "max_days": 3,
                            "min_days": 2,
                            "start_days": 3,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 2,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 4,
                            "start_days": 1,
                            "warning": "eat_soon"
                          },
                          {
                            "band": "ambient",
                            "end_days": 4,
                            "level": 3,
                            "max_days": 1,
                            "min_days": 0,
                            "start_days": 3,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 3,
                            "level": 3,
                            "max_days": 3,
                            "min_days": 2,
                            "start_days": 2,
                            "warning": null
                          },
                          {
                            "band": "ambient",
                            "end_days": 1,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 4,
                            "start_days": 0,
                            "warning": "eat_soon"
                          },
                          {
                            "band": "ambient",
                            "end_days": 1,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          },
                          {
                            "band": "14-18C",
                            "end_days": 10,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 7,
                            "warning": "immature"
                          },
                          {
                            "band": "14-18C",
                            "end_days": 8,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": null
                          },
                          {
                            "band": "14-18C",
                            "end_days": 6,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 4,
                            "warning": null
                          },
                          {
                            "band": "14-18C",
                            "end_days": 2,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          },
                          {
                            "band": "10-13C",
                            "end_days": 12,
                            "level": 1,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 9,
                            "warning": "immature"
                          },
                          {
                            "band": "10-13C",
                            "end_days": 10,
                            "level": 2,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 7,
                            "warning": null
                          },
                          {
                            "band": "10-13C",
                            "end_days": 8,
                            "level": 3,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 5,
                            "warning": null
                          },
                          {
                            "band": "10-13C",
                            "end_days": 2,
                            "level": 4,
                            "max_days": 30,
                            "min_days": 0,
                            "start_days": 0,
                            "warning": "overripe"
                          }
                        ]
                      },
                      "updated_at": 1790000000.5,
                      "updated_by": "admin@coop.example"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad variety, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "variety": {
                    "value": {
                      "error": "invalid variety: a string of 1 to 64 characters",
                      "code": "invalid_variety"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin, tenant_admin and auditor), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The tenant has no rules for this variety.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: Ri6",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/market-limits": {
      "get": {
        "operationId": "listMarketLimits",
        "summary": "Market limits (maximum residue levels and bans)",
        "description": "Every entry by id, one page (`limit`, default 100, at most 200; `cursor` from the previous page), each with its status on `today`. Platform data, the same for every tenant. Allowed for every role. Not audited (a read).",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "market_limit_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 100).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 100
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of entries.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MarketLimitPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 1,
                      "market": "CN",
                      "product": "durian",
                      "analyte": "cadmium",
                      "kind": "max",
                      "value": 0.05,
                      "unit": "mg/kg",
                      "valid_from": "2023-06-30",
                      "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)",
                      "created_at": 1790000000.5,
                      "created_by": "migration",
                      "status": "in_force"
                    },
                    {
                      "id": 2,
                      "market": "CN",
                      "product": "durian",
                      "analyte": "auramine_o",
                      "kind": "banned",
                      "value": null,
                      "unit": "mg/kg",
                      "valid_from": "2025-01-10",
                      "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)",
                      "created_at": 1790000000.5,
                      "created_by": "migration",
                      "status": "in_force"
                    }
                  ],
                  "today": "2026-09-30",
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (a principal without a role), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createMarketLimit",
        "summary": "Record a market limit entry",
        "description": "Appends an entry; it applies from `valid_from` and supersedes the earlier entry of the same market, product and analyte from that date. Lab reports signed from that date are judged with it; stored results keep the limit they were judged with, and no trust tier is raised without a signed, passing lab report. Audited (`market_limit.create`, in the same transaction). Allowed for platform_admin only. Step-up (#87): a signed-in session of an account with two-step sign-in must have confirmed a code from its authenticator app (or a backup code) within the last 5 minutes and its password within the last 10 minutes, else 401 `mfa_step_up_required` before anything is done (no audit row): confirm both with POST /v1/auth/reauth, then repeat the request. A session of an account without two-step sign-in, API tokens and API clients are served as before.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MarketLimitCreate"
              },
              "example": {
                "market": "CN",
                "product": "durian",
                "analyte": "cadmium",
                "kind": "max",
                "value": 0.03,
                "valid_from": "2026-10-15",
                "source": "GB 2762-2026, 4.2 cadmium, fresh fruit 0.03 mg/kg"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The entry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MarketLimit"
                },
                "example": {
                  "id": 3,
                  "market": "CN",
                  "product": "durian",
                  "analyte": "cadmium",
                  "kind": "max",
                  "value": 0.03,
                  "valid_from": "2026-10-15",
                  "source": "GB 2762-2026, 4.2 cadmium, fresh fruit 0.03 mg/kg",
                  "unit": "mg/kg",
                  "created_at": 1790000000.5,
                  "created_by": "platform@croppath.example",
                  "status": "scheduled"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field (`unit` included) or a bad value, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "market": {
                    "value": {
                      "error": "invalid market: an ISO 3166-1 alpha-2 code in capitals, e.g. CN",
                      "code": "invalid_market"
                    }
                  },
                  "valid_from": {
                    "value": {
                      "error": "invalid valid_from: from today (2026-09-30) to 10 years ahead",
                      "code": "invalid_valid_from"
                    }
                  },
                  "value": {
                    "value": {
                      "error": "invalid value: a ban has no value",
                      "code": "invalid_value"
                    }
                  },
                  "source": {
                    "value": {
                      "error": "invalid source: the regulation that sets the limit, 1 to 1000 characters",
                      "code": "invalid_source"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: unit",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            },
            "x-sdk-description": "No valid session, API token or legacy token."
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "An entry for the same market, product, analyte and date exists. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit_exists": {
                    "value": {
                      "error": "limit exists: the market already has a limit for this analyte from that date",
                      "code": "limit_exists"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "Appends an entry; it applies from `valid_from` and supersedes the earlier entry of the same market, product and analyte from that date. Lab reports signed from that date are judged with it; stored results keep the limit they were judged with, and no trust tier is raised without a signed, passing lab report. Audited (`market_limit.create`, in the same transaction). Allowed for platform_admin only."
      }
    },
    "/v1/health": {
      "get": {
        "operationId": "getAdminHealth",
        "summary": "Operational status for the admin health page",
        "description": "The body of /healthz (outbound backlog, watched certificates with their expiry, MQTT, read-only mode, warnings) plus the database (dialect, schema version, a round trip), the external timestamp authority (mode, host, backlog) and whether the issuer key store is available. Allowed for platform_admin only. Not audited (a read). `no-store`.",
        "tags": [
          "ops"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "responses": {
          "200": {
            "description": "The status.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AdminHealth"
                },
                "example": {
                  "ok": true,
                  "outbound_backlog": {
                    "national": 0
                  },
                  "certificates": [
                    {
                      "path": "/certs/gw-01.pem",
                      "subject": "gw-01",
                      "not_after": "2027-01-01T00:00:00+00:00",
                      "remaining_s": 7776000,
                      "remaining_fraction": 0.5,
                      "expired": false
                    }
                  ],
                  "mqtt": {
                    "broker": "emqx:8883",
                    "connected": true
                  },
                  "db": {
                    "dialect": "postgresql",
                    "schema_version": 30,
                    "expected_schema_version": 30,
                    "round_trip_ms": 0.8
                  },
                  "tsa": {
                    "mode": "on",
                    "host": "freetsa.org",
                    "pending": 1,
                    "failing": 1,
                    "verified": 42
                  },
                  "issuer_keys": {
                    "available": true
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lab/samples/{id}": {
      "get": {
        "operationId": "getLabAssignment",
        "summary": "One of the lab's assigned samplings, with its report",
        "description": "A7 (#73): the lab portal's sampling page. One sampling assigned to the caller's lab, with its samples, its full report once stored (`LabReport`, with the custody of the key that signed it) and the lab's active server-held portal key. Allowed only for a lab user signed in with a session; another lab's sampling answers 404 like a missing one; every other role, and a lab principal without a lab (an API token), is refused 403.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Sampling id, as `GET /v1/lab/samples` lists it.",
            "schema": {
              "type": "string"
            },
            "example": "41"
          }
        ],
        "responses": {
          "200": {
            "description": "The sampling.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabAssignmentDetail"
                },
                "example": {
                  "id": 41,
                  "exporter": "HTX Ngũ Hiệp",
                  "lot": {
                    "code": "LO-260928-014",
                    "product": "durian",
                    "variety": "Ri6",
                    "harvest_date": "2026-09-27"
                  },
                  "facility": {
                    "code": "VN-TGPH-021",
                    "name": "Cơ sở đóng gói Tân Phú",
                    "address": null,
                    "province": "Tiền Giang",
                    "district": "Cai Lậy"
                  },
                  "analytes": [
                    "cadmium",
                    "auramine_o"
                  ],
                  "sample_count": 3,
                  "selected_at": 1790000000.5,
                  "samples": [
                    {
                      "k": 1,
                      "fruit": "Q-014-0017",
                      "status": "selected"
                    },
                    {
                      "k": 2,
                      "fruit": "Q-014-0062",
                      "status": "selected"
                    },
                    {
                      "k": 3,
                      "fruit": "Q-014-0109",
                      "status": "selected"
                    }
                  ],
                  "report": null,
                  "portal_key": {
                    "kid": "LAB-VN-118.portal"
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "404": {
            "description": "No such sampling, or one assigned to another lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 41",
                  "code": "not_found"
                }
              }
            }
          }
        }
      }
    },
    "/v1/lab/samples/{id}/entry": {
      "post": {
        "operationId": "enterLabReport",
        "summary": "Enter the lab results of an assigned sampling in the portal",
        "description": "A7 (#73): the lab portal's result form for one of the lab's samplings. The server builds the report document from the entry (`LabPortalEntry`: version 1, the lab, the sampling, the server's time as `signed_at`), signs it with the lab's active server-held key (custody `server`, generated by `POST /v1/labs/{code}/portal-key`) and stores it exactly as `POST /v1/lab/samples/{id}/results` stores an uploaded signed report (verification, market limits, sample statuses, the `lab_result_failed` alert and lab hold). The report's `key_custody` is `server`: the public record and the credential state that the platform, not the lab, holds the key, and the lab step never counts the result as signed by the accredited lab (ADR 0001: at most Cross-checked). Audited (`lab_report.enter`). Allowed only for a lab user signed in with a session, for its own lab's samplings (another lab's sampling answers 404 like a missing one); every other role, and a lab principal without a lab (an API token), is refused 403.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Sampling id, as `GET /v1/lab/samples` lists it.",
            "schema": {
              "type": "string"
            },
            "example": "41"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabPortalEntry"
              },
              "example": {
                "report_no": "KN-260929-0071",
                "report_sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
                "results": [
                  {
                    "sample": 1,
                    "analyte": "cadmium",
                    "outcome": "measured",
                    "value": 0.018,
                    "unit": "mg/kg",
                    "lod": 0.002,
                    "method": "ICP-MS"
                  },
                  {
                    "sample": 1,
                    "analyte": "auramine_o",
                    "outcome": "not_detected",
                    "unit": "mg/kg",
                    "lod": 0.001,
                    "method": "LC-MS/MS"
                  },
                  {
                    "sample": 2,
                    "analyte": "cadmium",
                    "outcome": "measured",
                    "value": 0.018,
                    "unit": "mg/kg",
                    "lod": 0.002,
                    "method": "ICP-MS"
                  },
                  {
                    "sample": 2,
                    "analyte": "auramine_o",
                    "outcome": "not_detected",
                    "unit": "mg/kg",
                    "lod": 0.001,
                    "method": "LC-MS/MS"
                  },
                  {
                    "sample": 3,
                    "analyte": "cadmium",
                    "outcome": "measured",
                    "value": 0.018,
                    "unit": "mg/kg",
                    "lod": 0.002,
                    "method": "ICP-MS"
                  },
                  {
                    "sample": 3,
                    "analyte": "auramine_o",
                    "outcome": "not_detected",
                    "unit": "mg/kg",
                    "lod": 0.001,
                    "method": "LC-MS/MS"
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The stored report.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabReport"
                },
                "example": {
                  "report_no": "KN-260929-0071",
                  "lab": "LAB-VN-118",
                  "kid": "LAB-VN-118.portal",
                  "key_custody": "server",
                  "market": "CN",
                  "signed_at": 1790671200.0,
                  "report_sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
                  "passed": true,
                  "analytes": [
                    {
                      "analyte": "auramine_o",
                      "passed": true
                    },
                    {
                      "analyte": "cadmium",
                      "passed": true
                    }
                  ],
                  "results": [
                    {
                      "sample": 1,
                      "analyte": "auramine_o",
                      "outcome": "not_detected",
                      "value": null,
                      "unit": "mg/kg",
                      "lod": 0.001,
                      "method": "LC-MS/MS",
                      "limit": {
                        "kind": "banned",
                        "value": null,
                        "unit": "mg/kg",
                        "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 1,
                      "analyte": "cadmium",
                      "outcome": "measured",
                      "value": 0.018,
                      "unit": "mg/kg",
                      "lod": 0.002,
                      "method": "ICP-MS",
                      "limit": {
                        "kind": "max",
                        "value": 0.05,
                        "unit": "mg/kg",
                        "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 2,
                      "analyte": "auramine_o",
                      "outcome": "not_detected",
                      "value": null,
                      "unit": "mg/kg",
                      "lod": 0.001,
                      "method": "LC-MS/MS",
                      "limit": {
                        "kind": "banned",
                        "value": null,
                        "unit": "mg/kg",
                        "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 2,
                      "analyte": "cadmium",
                      "outcome": "measured",
                      "value": 0.018,
                      "unit": "mg/kg",
                      "lod": 0.002,
                      "method": "ICP-MS",
                      "limit": {
                        "kind": "max",
                        "value": 0.05,
                        "unit": "mg/kg",
                        "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 3,
                      "analyte": "auramine_o",
                      "outcome": "not_detected",
                      "value": null,
                      "unit": "mg/kg",
                      "lod": 0.001,
                      "method": "LC-MS/MS",
                      "limit": {
                        "kind": "banned",
                        "value": null,
                        "unit": "mg/kg",
                        "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
                      },
                      "passed": true
                    },
                    {
                      "sample": 3,
                      "analyte": "cadmium",
                      "outcome": "measured",
                      "value": 0.018,
                      "unit": "mg/kg",
                      "lod": 0.002,
                      "method": "ICP-MS",
                      "limit": {
                        "kind": "max",
                        "value": 0.05,
                        "unit": "mg/kg",
                        "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
                      },
                      "passed": true
                    }
                  ],
                  "origin": [],
                  "submitted_by": "lab@lab.example",
                  "received_at": 1790671260.5,
                  "report_pdf": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a missing or unknown member, a result outside the sampling or an incomplete report, a bad value, unit or detection limit, a bad origin result (outcome, region), a signed_at before the draw or in the future, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "incomplete": {
                    "value": {
                      "error": "incomplete results: no cadmium result for sample 3 (1 missing)",
                      "code": "incomplete_results"
                    }
                  },
                  "unit": {
                    "value": {
                      "error": "invalid results[0].unit: mg/kg",
                      "code": "invalid_results_0_unit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the sampling's company is leaving CropPath or has left, whatever company the lab user belongs to; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sampling, or one assigned to another lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 41",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lab holds no active server-held key, the sampling already has a report (nothing is overwritten), the lab's report number is taken, or the lab is not in force. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "reported": {
                    "value": {
                      "error": "sampling already reported",
                      "code": "sampling_already_reported"
                    }
                  },
                  "number": {
                    "value": {
                      "error": "report number taken",
                      "code": "report_number_taken"
                    }
                  },
                  "lab": {
                    "value": {
                      "error": "lab not in force: suspended, or its accreditation expired before the signed date",
                      "code": "lab_not_in_force"
                    }
                  },
                  "no_portal_key": {
                    "value": {
                      "error": "no portal key: the lab holds no active server-held key to sign portal entries",
                      "code": "no_portal_key"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "The server cannot read the lab's server-held key: no key-encryption key is configured (AGRITRACE_ISSUER_KEK) or its file does not decrypt; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                  "code": "issuer_keys_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/lab/samples/{id}/report-pdf": {
      "put": {
        "operationId": "attachLabReportPdf",
        "summary": "Store the PDF original of a lab report",
        "description": "A7 (#73, owner decision 4): the PDF original of the report of one of the lab's samplings, sent after the report was stored by either `POST /v1/lab/samples/{id}/results` or `POST /v1/lab/samples/{id}/entry`. The body is the PDF itself. Content-Type must be `application/pdf` (parameters ignored) and the bytes must start with `%PDF-`. The body is at most 1 MiB and must hash to the report's `report_sha256`. The file is stored once as a staff-only attachment owned by the sampling's tenant: only its tenant-wide staff read the bytes with `GET /v1/attachments/{sha256}`, a facility-scoped grant does not. The report links it as `report_pdf`. Nothing public changes: the public record keeps `lab.report_url` null and never names the file. It changes no verdict and no trust tier. A repeat of a stored PDF answers 200 and changes nothing, but its bytes are still checked against the report. Audited (`lab_report.attach_pdf`: the hash, media type and size, never the bytes). Allowed only for a lab user, for its own lab's samplings (another lab's sampling answers 404 like a missing one); every other role, and a lab principal without a lab (an API token), is refused 403.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Sampling id, as `GET /v1/lab/samples` lists it.",
            "schema": {
              "type": "string"
            },
            "example": "41"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/pdf": {
              "schema": {
                "type": "string",
                "contentMediaType": "application/pdf"
              },
              "example": "%PDF-1.7 ... (binary PDF bytes)"
            }
          }
        },
        "responses": {
          "200": {
            "description": "The sampling's tenant already holds this PDF; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AttachmentStored"
                },
                "example": {
                  "sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
                  "media_type": "application/pdf",
                  "size": 182344
                }
              }
            }
          },
          "201": {
            "description": "Stored and linked from the report as `report_pdf`.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AttachmentStored"
                },
                "example": {
                  "sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
                  "media_type": "application/pdf",
                  "size": 182344
                }
              }
            }
          },
          "400": {
            "description": "A missing or malformed Content-Length, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_content_length": {
                    "value": {
                      "error": "bad content length",
                      "code": "bad_content_length"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the sampling's company is leaving CropPath or has left, whatever company the lab user belongs to; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sampling, or one assigned to another lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 41",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The sampling has no report yet: the PDF follows the report.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "no report yet: store the sampling's report before its PDF",
                  "code": "no_report_yet"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "415": {
            "description": "Not declared as `application/pdf`, or bytes that do not start with the PDF signature `%PDF-`; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unsupported_media_type": {
                    "value": {
                      "error": "unsupported media type",
                      "code": "unsupported_media_type"
                    }
                  },
                  "content_does_not_match_the_media_type": {
                    "value": {
                      "error": "content does not match the media type",
                      "code": "content_does_not_match_the_media_type"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "The body does not hash to the report's `report_sha256`: it is not the file the report names; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "report pdf mismatch: the file does not hash to the report's report_sha256",
                  "code": "report_pdf_mismatch"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/portal-key": {
      "post": {
        "operationId": "generateLabPortalKey",
        "summary": "Generate a lab's server-held portal key",
        "description": "A7 (#73): generates an EC P-256 key pair for the lab whose private key the platform keeps (custody `server`: encrypted under the deployment's key-encryption key, never returned, logged or audited) to sign the results the lab's portal users enter. A lab holds at most one active server-held key: revoke it (`POST /v1/labs/{code}/keys/{kid}/revoke`, which also deletes the private key) before generating another. Key ids share one namespace with device, gateway and lab keys. Audited (`lab_key.generate`). Allowed for platform_admin only: holding a lab's key is the platform's custody decision.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabPortalKeyCreate"
              },
              "example": {
                "kid": "LAB-VN-118.portal"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabKey"
                },
                "example": {
                  "kid": "LAB-VN-118.portal",
                  "lab": "LAB-VN-118",
                  "status": "active",
                  "created_at": 1790000000.5,
                  "revoked_at": null,
                  "revoke_reason": null,
                  "revoked_by": null,
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "custody": "server"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field (the server generates the pair; give only its kid), a bad kid, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: the server generates the key pair; give only its kid",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The key id is taken (by any key) or reserved, or the lab already holds an active server-held key. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "kid_taken": {
                    "value": {
                      "error": "key id taken",
                      "code": "key_id_taken"
                    }
                  },
                  "portal_key_exists": {
                    "value": {
                      "error": "portal key exists: revoke the lab's active server-held key first",
                      "code": "portal_key_exists"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK), or the store cannot be used; nothing changed. Retry after `Retry-After` seconds once it is configured.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                  "code": "issuer_keys_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/reports/{id}": {
      "get": {
        "operationId": "getReport",
        "summary": "One public mismatch report with its fruit's scan history (staff triage)",
        "description": "The report as the list shows it, with the contact (null once erased), and the reported fruit's scan history (A8, #74; ReportDetail): the newest 50 scans, newest first, each its number, time, country, region, city and device class, never an address or its hash. A read with two bounded statements, not audited, `no-store`. Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant); another tenant's report answers like a missing one.",
        "tags": [
          "reports"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "report_triage"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The report id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          }
        ],
        "responses": {
          "200": {
            "description": "The report and its fruit's scan history.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReportDetail"
                },
                "example": {
                  "id": 12,
                  "fruit": {
                    "code": "Q-0928-014-0003",
                    "public_id": "73879f17d0930440809333f141385eb6"
                  },
                  "lot": {
                    "code": "LO-260928-014",
                    "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
                  },
                  "category": "scanned_many",
                  "note": "Mã đã bị quét ở nhiều nơi.",
                  "contact": "zalo 0901 234 567",
                  "status": "open",
                  "outcome": null,
                  "created_at": 1790000000.5,
                  "resolved_at": null,
                  "scans": {
                    "total": 4,
                    "truncated": false,
                    "items": [
                      {
                        "scan_no": 4,
                        "at": 1789999000.0,
                        "country": "VN",
                        "region": "Hà Nội",
                        "city": "Hà Nội",
                        "ua_class": "mobile"
                      },
                      {
                        "scan_no": 3,
                        "at": 1789990000.0,
                        "country": "VN",
                        "region": "Gia Lai",
                        "city": "Pleiku",
                        "ua_class": "mobile"
                      },
                      {
                        "scan_no": 2,
                        "at": 1789980000.0,
                        "country": "VN",
                        "region": "Đắk Lắk",
                        "city": null,
                        "ua_class": "desktop"
                      },
                      {
                        "scan_no": 1,
                        "at": 1789970000.0,
                        "country": "VN",
                        "region": "Đắk Lắk",
                        "city": "Buôn Ma Thuột",
                        "ua_class": "other"
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such report of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/captured-events": {
      "get": {
        "operationId": "listLotCapturedEvents",
        "summary": "EPCIS events partners captured for a lot",
        "description": "The lot's events captured from partner systems (#167, `POST /v1/epcis/capture`): those naming the lot or one of its cartons, and those naming the shipment that carries it; oldest capture first, one page at a time. Each is the partner's statement (`source` `partner_capture`, `tier` `self_declared`, ADR 0001) with the step it records, its times and places as sent, who captured it (an opaque operator id: `user-<id>`, `token-<id>` or `legacy-<hash>`) and the lot, carton and shipment codes it names. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities, and only the events whose every lot, carton and shipment is in those facilities: an event that also names a record of another facility is left out). Not audited (a read).",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IDEyfQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the lot's captured events.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CapturedEventPage"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "items": [
                    {
                      "event_id": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000001",
                      "capture_id": 12,
                      "event_type": "ObjectEvent",
                      "biz_step": "commissioning",
                      "step": "harvest",
                      "action": "ADD",
                      "event_time": "2026-09-27T07:30:00.000+07:00",
                      "event_time_zone_offset": "+07:00",
                      "read_point": null,
                      "biz_location": null,
                      "source": "partner_capture",
                      "tier": "self_declared",
                      "captured_by": "token-3",
                      "captured_at": 1791504000.0,
                      "references": [
                        {
                          "kind": "lot",
                          "code": "LO-260928-014"
                        }
                      ]
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "Bad request id, limit or cursor.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/epcis/capture": {
      "post": {
        "operationId": "captureEpcis",
        "summary": "Capture an EPCIS 2.0 document from a partner system",
        "x-sdk-description": "Takes one GS1 EPCIS 2.0 JSON-LD document (#167; /developers/downloads/epcis-capture.md) from a partner system (an ERP, a packing house, a buyer's EPCIS repository) holding an API token of the tenant, and answers a report with one line per event in document order. The document must be an `EPCISDocument` naming the EPCIS 2.0 context, `schemaVersion` 2.x, with at most 500 events in `epcisBody.eventList` (the body at most 1 MiB); otherwise it is refused as a whole (400, 413) and nothing is written. Each event is checked against the GS1 EPCIS 2.0 JSON schema's rules for the members read and is `accepted` (stored), a `duplicate` (the tenant already holds this `eventID` with the same content: a retry is safe) or `rejected` with a code: `invalid_event` (with a `detail` naming the member), `unsupported_event_type` (only ObjectEvent, AggregationEvent and TransformationEvent), `missing_event_id`, `unsupported_action` (DELETE), `unsupported_error_declaration`, `unsupported_biz_step` (only commissioning, the harvest, receiving, packing and shipping, as bare CBV terms or `https://ref.gs1.org/cbv/BizStep-<term>`), `event_too_large` (over 32 KiB), `event_id_conflict` (the `eventID` is held with other content), `no_reference` or `unknown_reference` (an identifier that is not a lot, carton or shipment of the tenant: lots `urn:agritrace:lot:<code>` or `https://id.gs1.org/01/<gtin>/10/<code>` as EPC classes, cartons `urn:agritrace:carton:<code>` and shipments `urn:agritrace:shipment:<code>` as EPCs, shipments also as business transactions). Nothing is ever created from a capture. Captured events are the partner's statements: `source` `partner_capture`, `tier` `self_declared` (ADR 0001); they never feed the trust tiers or the public pages. One audit row per request (`epcis.capture`: the capture id and the counts). Allowed for tenant_admin and platform_admin acting for the tenant; an operator or auditor token is refused. An OAuth2 access token (#171) needs the dedicated `epcis_capture` scope, which no other scope implies (403 `role not permitted` otherwise).",
        "description": "Takes one GS1 EPCIS 2.0 JSON-LD document (#167; /developers/downloads/epcis-capture.md) from a partner system (an ERP, a packing house, a buyer's EPCIS repository) holding an API token of the tenant, and answers a report with one line per event in document order. The document must be an `EPCISDocument` naming the EPCIS 2.0 context, `schemaVersion` 2.x, with at most 500 events in `epcisBody.eventList` (the body at most 1 MiB); otherwise it is refused as a whole (400, 413) and nothing is written. Each event is checked against the GS1 EPCIS 2.0 JSON schema's rules for the members read and is `accepted` (stored), a `duplicate` (the tenant already holds this `eventID` with the same content: a retry is safe) or `rejected` with a code: `invalid_event` (with a `detail` naming the member), `unsupported_event_type` (only ObjectEvent, AggregationEvent and TransformationEvent), `missing_event_id`, `unsupported_action` (DELETE), `unsupported_error_declaration`, `unsupported_biz_step` (only commissioning, the harvest, receiving, packing, shipping and sensor_reporting, as bare CBV terms or `https://ref.gs1.org/cbv/BizStep-<term>`; sensor_reporting only on an ObjectEvent with action OBSERVE and a `sensorElementList`), `event_too_large` (over 32 KiB, or a sensor_reporting event with more than 20 sensor elements or 200 sensor reports), `event_id_conflict` (the `eventID` is held with other content), `no_reference` or `unknown_reference` (an identifier that is not a lot, carton or shipment of the tenant: lots `urn:agritrace:lot:<code>` or `https://id.gs1.org/01/<gtin>/10/<code>` as EPC classes, cartons `urn:agritrace:carton:<code>` and shipments `urn:agritrace:shipment:<code>` as EPCs, shipments also as business transactions). A sensor_reporting event (#238) is the partner's sensor data about a lot, carton or shipment it names, its sensor elements checked member by member against the GS1 schema's sensorElement, sensorMetadata and sensorReport (`invalid_event` naming the member); one that names none of the tenant's records, such as a growing area's daily summary, is `no_reference`. Nothing is ever created from a capture. Captured events are the partner's statements: `source` `partner_capture`, `tier` `self_declared` (ADR 0001); they never feed the trust tiers, the sensor readings or the public pages. One audit row per request (`epcis.capture`: the capture id and the counts). Allowed for tenant_admin and platform_admin acting for the tenant; an operator or auditor token is refused. An OAuth2 access token (#171) needs the dedicated `epcis_capture` scope, which no other scope implies (403 `role not permitted` otherwise).",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "epcis_capture"
            ]
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/ld+json": {
              "schema": {
                "$ref": "#/components/schemas/EpcisDocument"
              },
              "example": {
                "@context": [
                  "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld"
                ],
                "type": "EPCISDocument",
                "schemaVersion": "2.0",
                "creationDate": "2026-10-09T08:00:00Z",
                "epcisBody": {
                  "eventList": [
                    {
                      "type": "ObjectEvent",
                      "eventID": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000001",
                      "eventTime": "2026-09-27T07:30:00.000+07:00",
                      "eventTimeZoneOffset": "+07:00",
                      "action": "ADD",
                      "bizStep": "commissioning",
                      "quantityList": [
                        {
                          "epcClass": "urn:agritrace:lot:LO-260928-014",
                          "quantity": 500,
                          "uom": "KGM"
                        }
                      ]
                    },
                    {
                      "type": "AggregationEvent",
                      "eventID": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000002",
                      "eventTime": "2026-09-29T07:30:00.000+07:00",
                      "eventTimeZoneOffset": "+07:00",
                      "action": "ADD",
                      "bizStep": "packing",
                      "parentID": "urn:agritrace:carton:C-0928014-0001",
                      "childQuantityList": [
                        {
                          "epcClass": "urn:agritrace:lot:LO-260928-014",
                          "quantity": 8.6,
                          "uom": "KGM"
                        }
                      ]
                    },
                    {
                      "type": "ObjectEvent",
                      "eventID": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000003",
                      "eventTime": "2026-09-30T07:30:00.000+07:00",
                      "eventTimeZoneOffset": "+07:00",
                      "action": "OBSERVE",
                      "bizStep": "inspecting",
                      "quantityList": [
                        {
                          "epcClass": "urn:agritrace:lot:LO-260928-014"
                        }
                      ]
                    }
                  ]
                }
              }
            },
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EpcisDocument"
              },
              "example": {
                "@context": [
                  "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld"
                ],
                "type": "EPCISDocument",
                "schemaVersion": "2.0",
                "creationDate": "2026-10-09T08:00:00Z",
                "epcisBody": {
                  "eventList": [
                    {
                      "type": "ObjectEvent",
                      "eventID": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000001",
                      "eventTime": "2026-09-27T07:30:00.000+07:00",
                      "eventTimeZoneOffset": "+07:00",
                      "action": "ADD",
                      "bizStep": "commissioning",
                      "quantityList": [
                        {
                          "epcClass": "urn:agritrace:lot:LO-260928-014",
                          "quantity": 500,
                          "uom": "KGM"
                        }
                      ]
                    },
                    {
                      "type": "AggregationEvent",
                      "eventID": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000002",
                      "eventTime": "2026-09-29T07:30:00.000+07:00",
                      "eventTimeZoneOffset": "+07:00",
                      "action": "ADD",
                      "bizStep": "packing",
                      "parentID": "urn:agritrace:carton:C-0928014-0001",
                      "childQuantityList": [
                        {
                          "epcClass": "urn:agritrace:lot:LO-260928-014",
                          "quantity": 8.6,
                          "uom": "KGM"
                        }
                      ]
                    },
                    {
                      "type": "ObjectEvent",
                      "eventID": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000003",
                      "eventTime": "2026-09-30T07:30:00.000+07:00",
                      "eventTimeZoneOffset": "+07:00",
                      "action": "OBSERVE",
                      "bizStep": "inspecting",
                      "quantityList": [
                        {
                          "epcClass": "urn:agritrace:lot:LO-260928-014"
                        }
                      ]
                    }
                  ]
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The capture's per-event report.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EpcisCaptureReport"
                },
                "example": {
                  "capture_id": 12,
                  "events": 3,
                  "accepted": 2,
                  "duplicates": 0,
                  "rejected": 1,
                  "source": "partner_capture",
                  "tier": "self_declared",
                  "results": [
                    {
                      "index": 0,
                      "event_id": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000001",
                      "status": "accepted",
                      "step": "harvest",
                      "references": [
                        {
                          "kind": "lot",
                          "code": "LO-260928-014"
                        }
                      ]
                    },
                    {
                      "index": 1,
                      "event_id": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000002",
                      "status": "accepted",
                      "step": "pack",
                      "references": [
                        {
                          "kind": "lot",
                          "code": "LO-260928-014"
                        },
                        {
                          "kind": "carton",
                          "code": "C-0928014-0001"
                        }
                      ]
                    },
                    {
                      "index": 2,
                      "event_id": "urn:uuid:6f1c2a3b-0000-4000-8000-000000000003",
                      "status": "rejected",
                      "code": "unsupported_biz_step",
                      "detail": "bizStep 'inspecting' is not captured"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Bad request id, invalid JSON, or a document refused as a whole; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "document": {
                    "value": {
                      "error": "invalid document: @context must name the EPCIS 2.0 context",
                      "code": "invalid_document"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "413": {
            "description": "The body is over 1 MiB, or the document holds more than 500 events.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "body": {
                    "value": {
                      "error": "body too large",
                      "code": "body_too_large"
                    }
                  },
                  "events": {
                    "value": {
                      "error": "too many events: at most 500 per document",
                      "code": "too_many_events"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ]
      }
    },
    "/v1/sessions/{id}/fruits/batch": {
      "post": {
        "operationId": "allocateFruitBatch",
        "summary": "Allocate up to 1,000 fruits of a session",
        "description": "Allocates `count` fruits of an open measurement session (consecutive n of its lot) with their label payloads, to print labels ahead of the line: a batch issues no set_session command to the session's devices. Audited once (`fruit.batch_allocate`). Allowed like the single allocation. Atomic: the batch commits whole or not at all, in one transaction with its one audit row. Every item is validated first and every invalid item is reported (400 `invalid_batch`, `items` by index); then the items are applied in order and the first one the stored state refuses rolls the batch back and is reported (`batch_rejected` with the item's own status and `items` naming it). At most 1,000 items and a body within 1 MiB. #326: with `label_code=1` each label payload also has the fruit's lookup code (`label_code`, #288), the 15-character code a label prints beside the QR code for a person whose QR code cannot be scanned; the scan page and `GET /v1/public/resolve` read it. Rate limited per tenant and caller (bursts of 10 batches, then one every 6 seconds).",
        "x-sdk-description": "Allocates `count` fruits of an open measurement session (consecutive n of its lot) with their label payloads, to print labels ahead of the line: a batch issues no set_session command to the session's devices. Audited once (`fruit.batch_allocate`). Allowed like the single allocation. Atomic: the batch commits whole or not at all, in one transaction with its one audit row. Every item is validated first and every invalid item is reported (400 `invalid_batch`, `items` by index); then the items are applied in order and the first one the stored state refuses rolls the batch back and is reported (`batch_rejected` with the item's own status and `items` naming it). At most 1,000 items and a body within 1 MiB. Rate limited per tenant and caller (bursts of 10 batches, then one every 6 seconds).",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Measurement session id.",
            "schema": {
              "type": "string"
            },
            "example": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "name": "label_code",
            "in": "query",
            "required": false,
            "description": "#326: `1` adds each fruit's lookup code to its label payload (`items[].label.label_code`); `0` or none leaves it out and answers exactly as before; any other value is refused (400 `bad label_code`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BatchCount"
              },
              "example": {
                "count": 200
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The batch, committed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FruitBatchResult"
                },
                "example": {
                  "batch_id": 12,
                  "count": 1,
                  "items": [
                    {
                      "tenant": "coop-dl",
                      "code": "Q-014-0129",
                      "n": 129,
                      "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
                      "lot": "LO-260928-014",
                      "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                      "line": "A2",
                      "operator": "user-7",
                      "status": "awaiting_device",
                      "labels_printed_at": 1790000000.5,
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5,
                      "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
                      "label": {
                        "code": "Q-014-0129",
                        "lot": "LO-260928-014",
                        "n": 129,
                        "line": "A2",
                        "operator": "user-7",
                        "printed_at": 1790000000.5,
                        "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
                      },
                      "level": null,
                      "level_pred": null,
                      "maturity_class": null,
                      "confidence": null,
                      "model": null,
                      "measured_at": null,
                      "weight_kg": null,
                      "level_sensory": null,
                      "override": false,
                      "pending_review": false,
                      "grade": null,
                      "eating_window": null,
                      "record_tier": null,
                      "knock_envelope_id": null,
                      "scale_envelope_id": null,
                      "override_envelope_id": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body of the wrong shape, invalid items (`invalid_batch`, each one listed), an item the stored state refuses as invalid (`batch_rejected`) or a bad X-Request-Id; a malformed or repeated Idempotency-Key header; or `label_code` not 0 or 1.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_batch": {
                    "value": {
                      "error": "invalid batch: 1 of the items failed validation",
                      "code": "invalid_batch",
                      "items": [
                        {
                          "index": 3,
                          "status": 400,
                          "error": "invalid kg: a number above 0 and at most 1000000",
                          "code": "invalid_kg"
                        }
                      ]
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "bad_label_code": {
                    "value": {
                      "error": "bad label_code",
                      "code": "bad_label_code"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "Invalid JSON, a body of the wrong shape, invalid items (`invalid_batch`, each one listed), an item the stored state refuses as invalid (`batch_rejected`) or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "invalid_batch": {
                      "value": {
                        "error": "invalid batch: 1 of the items failed validation",
                        "code": "invalid_batch",
                        "items": [
                          {
                            "index": 3,
                            "status": 400,
                            "error": "invalid kg: a number above 0 and at most 1000000",
                            "code": "invalid_kg"
                          }
                        ]
                      }
                    },
                    "invalid_idempotency_key": {
                      "value": {
                        "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                        "code": "invalid_idempotency_key"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such measurement session for this tenant: a session of another tenant, or of a facility outside an operator's scope, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: ms-3c1f",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The session's lot is past open, or the session is paused or closed; or the Idempotency-Key's batch was applied more than 24 hours ago (its response is no longer stored) for this route, path id and body. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "session_is_closed": {
                    "value": {
                      "error": "session is closed",
                      "code": "session_is_closed"
                    }
                  },
                  "idempotency_key_already_used": {
                    "value": {
                      "error": "idempotency key already used: batch 12",
                      "code": "idempotency_key_already_used"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "description": "The Idempotency-Key was used before with another request (another method, path, query or body): `idempotency_key_mismatch` within 24 hours, `idempotency_key_reused_with_a_different_request` for a batch key older than that; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "idempotency_key_mismatch": {
                    "value": {
                      "error": "idempotency key mismatch: the key was used with another request",
                      "code": "idempotency_key_mismatch"
                    }
                  },
                  "idempotency_key_reused_with_a_different_request": {
                    "value": {
                      "error": "idempotency key reused with a different request",
                      "code": "idempotency_key_reused_with_a_different_request"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "description": "Too many batch requests from this caller of this tenant (bursts of 10, then one every 6 seconds); nothing was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/cartons/batch": {
      "post": {
        "operationId": "createCartonBatch",
        "summary": "Create up to 1,000 cartons of a lot",
        "description": "Creates `count` empty cartons of the lot (the next numbers, codes, public ids and GS1 serials). Audited once (`carton.batch_create`). Allowed like the single carton. Atomic: the batch commits whole or not at all, in one transaction with its one audit row. Every item is validated first and every invalid item is reported (400 `invalid_batch`, `items` by index); then the items are applied in order and the first one the stored state refuses rolls the batch back and is reported (`batch_rejected` with the item's own status and `items` naming it). At most 1,000 items and a body within 1 MiB. Rate limited per tenant and caller (bursts of 10 batches, then one every 6 seconds).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BatchCount"
              },
              "example": {
                "count": 40
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The batch, committed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CartonBatchResult"
                },
                "example": {
                  "batch_id": 12,
                  "count": 1,
                  "items": [
                    {
                      "tenant": "coop-dl",
                      "code": "C-014-0017",
                      "lot": "LO-260928-014",
                      "carton_no": 17,
                      "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                      "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                      "net_mass_kg": 8.53,
                      "fruit_count": 3,
                      "fruit_mass_kg": 8.89,
                      "labels_printed_at": 1790000300.5,
                      "created_by": "packer@coop.example",
                      "created_at": 1790000300.5,
                      "updated_at": 1790000310.0,
                      "fruits": [
                        "Q-014-0049",
                        "Q-014-0050",
                        "Q-014-0052"
                      ]
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body of the wrong shape, invalid items (`invalid_batch`, each one listed), an item the stored state refuses as invalid (`batch_rejected`) or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_batch": {
                    "value": {
                      "error": "invalid batch: 1 of the items failed validation",
                      "code": "invalid_batch",
                      "items": [
                        {
                          "index": 3,
                          "status": 400,
                          "error": "invalid kg: a number above 0 and at most 1000000",
                          "code": "invalid_kg"
                        }
                      ]
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's scope, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot is not open or closed; a carton past the lot's 9999 (`batch_rejected`, its index); or the Idempotency-Key's batch was applied more than 24 hours ago (its response is no longer stored) for this route, path id and body. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_is_packed": {
                    "value": {
                      "error": "lot is packed",
                      "code": "lot_is_packed"
                    }
                  },
                  "batch_rejected": {
                    "value": {
                      "error": "batch rejected: item 5 failed",
                      "code": "batch_rejected",
                      "items": [
                        {
                          "index": 5,
                          "status": 409,
                          "error": "too many cartons: a lot holds at most 9999",
                          "code": "too_many_cartons"
                        }
                      ]
                    }
                  },
                  "idempotency_key_already_used": {
                    "value": {
                      "error": "idempotency key already used: batch 12",
                      "code": "idempotency_key_already_used"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "description": "The Idempotency-Key was used before with another request (another method, path, query or body): `idempotency_key_mismatch` within 24 hours, `idempotency_key_reused_with_a_different_request` for a batch key older than that; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "idempotency_key_mismatch": {
                    "value": {
                      "error": "idempotency key mismatch: the key was used with another request",
                      "code": "idempotency_key_mismatch"
                    }
                  },
                  "idempotency_key_reused_with_a_different_request": {
                    "value": {
                      "error": "idempotency key reused with a different request",
                      "code": "idempotency_key_reused_with_a_different_request"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "description": "Too many batch requests from this caller of this tenant (bursts of 10, then one every 6 seconds); nothing was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/carton-contents/batch": {
      "post": {
        "operationId": "setCartonContentsBatch",
        "summary": "Set the contents of up to 1,000 cartons of a lot",
        "description": "Replaces the fruits and net mass of each listed carton of the lot, in request order (an item may take a fruit an earlier item removed from another carton); a carton at most once per batch. Audited once (`carton.contents.batch_set`). Allowed like the single contents change. Atomic: the batch commits whole or not at all, in one transaction with its one audit row. Every item is validated first and every invalid item is reported (400 `invalid_batch`, `items` by index); then the items are applied in order and the first one the stored state refuses rolls the batch back and is reported (`batch_rejected` with the item's own status and `items` naming it). At most 1,000 items and a body within 1 MiB. Rate limited per tenant and caller (bursts of 10 batches, then one every 6 seconds).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CartonContentsBatch"
              },
              "example": {
                "items": [
                  {
                    "carton": "C-014-0017",
                    "fruits": [
                      "Q-014-0129",
                      "Q-014-0130"
                    ],
                    "net_mass_kg": 6.1
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The batch, committed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CartonContentsBatchResult"
                },
                "example": {
                  "batch_id": 12,
                  "count": 1,
                  "items": [
                    {
                      "tenant": "coop-dl",
                      "code": "C-014-0017",
                      "lot": "LO-260928-014",
                      "carton_no": 17,
                      "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                      "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
                      "net_mass_kg": 6.1,
                      "fruit_count": 2,
                      "fruit_mass_kg": 6.0,
                      "labels_printed_at": 1790000300.5,
                      "created_by": "packer@coop.example",
                      "created_at": 1790000300.5,
                      "updated_at": 1790000310.0,
                      "fruits": [
                        "Q-014-0129",
                        "Q-014-0130"
                      ]
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body of the wrong shape, invalid items (`invalid_batch`, each one listed), an item the stored state refuses as invalid (`batch_rejected`) or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_batch": {
                    "value": {
                      "error": "invalid batch: 1 of the items failed validation",
                      "code": "invalid_batch",
                      "items": [
                        {
                          "index": 3,
                          "status": 400,
                          "error": "invalid kg: a number above 0 and at most 1000000",
                          "code": "invalid_kg"
                        }
                      ]
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "batch_rejected": {
                    "value": {
                      "error": "batch rejected: item 2 failed",
                      "code": "batch_rejected",
                      "items": [
                        {
                          "index": 2,
                          "status": 400,
                          "error": "unknown fruit: Q-999-0001 is not a fruit of lot LO-260928-014",
                          "code": "unknown_fruit"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant (as a missing one), or an item's carton is not one of the lot's (`batch_rejected`, its index).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_found": {
                    "value": {
                      "error": "not found: LO-260928-014",
                      "code": "not_found"
                    }
                  },
                  "batch_rejected": {
                    "value": {
                      "error": "batch rejected: item 1 failed",
                      "code": "batch_rejected",
                      "items": [
                        {
                          "index": 1,
                          "status": 404,
                          "error": "not found: C-014-0999",
                          "code": "not_found"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lot is not open or closed; a fruit not packable or in another carton (`batch_rejected`, its index); or the Idempotency-Key's batch was applied more than 24 hours ago (its response is no longer stored) for this route, path id and body. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_is_packed": {
                    "value": {
                      "error": "lot is packed",
                      "code": "lot_is_packed"
                    }
                  },
                  "batch_rejected": {
                    "value": {
                      "error": "batch rejected: item 4 failed",
                      "code": "batch_rejected",
                      "items": [
                        {
                          "index": 4,
                          "status": 409,
                          "error": "fruit not packable: Q-014-0131 is rejected",
                          "code": "fruit_not_packable"
                        }
                      ]
                    }
                  },
                  "idempotency_key_already_used": {
                    "value": {
                      "error": "idempotency key already used: batch 12",
                      "code": "idempotency_key_already_used"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "description": "The Idempotency-Key was used before with another request (another method, path, query or body): `idempotency_key_mismatch` within 24 hours, `idempotency_key_reused_with_a_different_request` for a batch key older than that; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "idempotency_key_mismatch": {
                    "value": {
                      "error": "idempotency key mismatch: the key was used with another request",
                      "code": "idempotency_key_mismatch"
                    }
                  },
                  "idempotency_key_reused_with_a_different_request": {
                    "value": {
                      "error": "idempotency key reused with a different request",
                      "code": "idempotency_key_reused_with_a_different_request"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "description": "Too many batch requests from this caller of this tenant (bursts of 10, then one every 6 seconds); nothing was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/harvests/batch": {
      "post": {
        "operationId": "declareHarvestBatch",
        "summary": "Declare up to 1,000 harvests",
        "description": "Declares harvests across the growing areas the caller may write (tenant-entered, Self-declared, each checked like the single declaration); an area and date at most once per batch. Audited once (`growing_area.harvest.batch_declare`). Allowed like the single declaration. Atomic: the batch commits whole or not at all, in one transaction with its one audit row. Every item is validated first and every invalid item is reported (400 `invalid_batch`, `items` by index); then the items are applied in order and the first one the stored state refuses rolls the batch back and is reported (`batch_rejected` with the item's own status and `items` naming it). At most 1,000 items and a body within 1 MiB. Rate limited per tenant and caller (bursts of 10 batches, then one every 6 seconds).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/HarvestBatch"
              },
              "example": {
                "items": [
                  {
                    "growing_area": "VN-DL-SR-0123",
                    "harvest_date": "2026-09-27",
                    "kg": 1820
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The batch, committed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestBatchResult"
                },
                "example": {
                  "batch_id": 12,
                  "count": 1,
                  "items": [
                    {
                      "id": 7,
                      "growing_area": "VN-TGOR-0387",
                      "harvest_date": "2026-09-27",
                      "season": "2026",
                      "kg": 1820.0,
                      "source": "self_declared",
                      "declared_by": "admin@coop-dl",
                      "declared_at": 1790500000.0
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body of the wrong shape, invalid items (`invalid_batch`, each one listed), an item the stored state refuses as invalid (`batch_rejected`) or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_batch": {
                    "value": {
                      "error": "invalid batch: 1 of the items failed validation",
                      "code": "invalid_batch",
                      "items": [
                        {
                          "index": 3,
                          "status": 400,
                          "error": "invalid kg: a number above 0 and at most 1000000",
                          "code": "invalid_kg"
                        }
                      ]
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). Also a `batch_rejected` naming an item whose area is an unowned, seeded one and the caller no platform admin. SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "An item's area is missing or another tenant's (`batch_rejected`, its index).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "batch rejected: item 0 failed",
                  "code": "batch_rejected",
                  "items": [
                    {
                      "index": 0,
                      "status": 404,
                      "error": "not found: VN-DL-SR-0999",
                      "code": "not_found"
                    }
                  ]
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "An item's area already has a declaration for its date (`batch_rejected`, its index); or the Idempotency-Key's batch was applied more than 24 hours ago (its response is no longer stored) for this route, path id and body. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "batch_rejected": {
                    "value": {
                      "error": "batch rejected: item 2 failed",
                      "code": "batch_rejected",
                      "items": [
                        {
                          "index": 2,
                          "status": 409,
                          "error": "harvest already declared: the area has a declaration for this date",
                          "code": "harvest_already_declared"
                        }
                      ]
                    }
                  },
                  "idempotency_key_already_used": {
                    "value": {
                      "error": "idempotency key already used: batch 12",
                      "code": "idempotency_key_already_used"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "description": "The Idempotency-Key was used before with another request (another method, path, query or body): `idempotency_key_mismatch` within 24 hours, `idempotency_key_reused_with_a_different_request` for a batch key older than that; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "idempotency_key_mismatch": {
                    "value": {
                      "error": "idempotency key mismatch: the key was used with another request",
                      "code": "idempotency_key_mismatch"
                    }
                  },
                  "idempotency_key_reused_with_a_different_request": {
                    "value": {
                      "error": "idempotency key reused with a different request",
                      "code": "idempotency_key_reused_with_a_different_request"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "description": "Too many batch requests from this caller of this tenant (bursts of 10, then one every 6 seconds); nothing was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/growers/batch": {
      "post": {
        "operationId": "createGrowerBatch",
        "summary": "Create up to 1,000 growers",
        "description": "Creates growers of the caller's tenant, each checked like the single creation. Audited once (`grower.batch_create`; ids and a consent count, never a name). Allowed like the single creation. Atomic: the batch commits whole or not at all, in one transaction with its one audit row. Every item is validated first and every invalid item is reported (400 `invalid_batch`, `items` by index); then the items are applied in order and the first one the stored state refuses rolls the batch back and is reported (`batch_rejected` with the item's own status and `items` naming it). At most 1,000 items and a body within 1 MiB. Rate limited per tenant and caller (bursts of 10 batches, then one every 6 seconds).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "growing_area_edit"
            ]
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowerBatch"
              },
              "example": {
                "items": [
                  {
                    "name": "Nguyễn Văn A",
                    "cooperative": "HTX Đắk Lắk"
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The batch, committed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowerBatchResult"
                },
                "example": {
                  "batch_id": 12,
                  "count": 1,
                  "items": [
                    {
                      "id": 12,
                      "tenant": "coop-dl",
                      "display_name": "Co-op member #12",
                      "cooperative": "HTX Ngu Hiep",
                      "public_consent": false,
                      "consent_at": null,
                      "consent_date": null,
                      "consent_scope": null,
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5,
                      "name": "Nguyen Van An"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body of the wrong shape, invalid items (`invalid_batch`, each one listed), an item the stored state refuses as invalid (`batch_rejected`) or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_batch": {
                    "value": {
                      "error": "invalid batch: 1 of the items failed validation",
                      "code": "invalid_batch",
                      "items": [
                        {
                          "index": 3,
                          "status": 400,
                          "error": "invalid kg: a number above 0 and at most 1000000",
                          "code": "invalid_kg"
                        }
                      ]
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (also a tenant_admin changing an unowned, seeded area), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The caller's tenant is not registered, or the Idempotency-Key's batch was applied more than 24 hours ago (its response is no longer stored) for this route, path id and body. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant_not_registered": {
                    "value": {
                      "error": "tenant not registered",
                      "code": "tenant_not_registered"
                    }
                  },
                  "idempotency_key_already_used": {
                    "value": {
                      "error": "idempotency key already used: batch 12",
                      "code": "idempotency_key_already_used"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "description": "The Idempotency-Key was used before with another request (another method, path, query or body): `idempotency_key_mismatch` within 24 hours, `idempotency_key_reused_with_a_different_request` for a batch key older than that; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "idempotency_key_mismatch": {
                    "value": {
                      "error": "idempotency key mismatch: the key was used with another request",
                      "code": "idempotency_key_mismatch"
                    }
                  },
                  "idempotency_key_reused_with_a_different_request": {
                    "value": {
                      "error": "idempotency key reused with a different request",
                      "code": "idempotency_key_reused_with_a_different_request"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "description": "Too many batch requests from this caller of this tenant (bursts of 10, then one every 6 seconds); nothing was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/records-export.csv": {
      "get": {
        "operationId": "getRecordsExportCsv",
        "summary": "Records-request export of the tenant's lots in a range (CSV)",
        "description": "The records of the tenant's lots CREATED in [start, end), one page at a time, the same rows as the per-lot export lot by lot (W1-3, #152). `start` and `end` are ISO 8601 dates or date-times (local time, +07:00, without an offset), at most 366 days apart. A page holds at most 50 lots whose cartons together stay within 9,999 (always one lot at least); a lot whose signed device events were cut is flagged by `X-Records-Truncated`, the CSV's truncation_notice row and the JSON's `truncated`; the next page's cursor is `next_cursor` (JSON) or the `X-Next-Cursor` header (CSV, absent on the last page). An audited read (`export.records`: the parsed range, the format, the lot and row counts), downloaded as an attachment, never cached. Allowed for tenant_admin, platform_admin acting for the tenant and auditor; operators and labs are refused; another tenant's lots never appear. An OAuth2 access token (#171) needs the dedicated `records_export` scope, which no other scope implies (403 `role not permitted` otherwise).",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "records_export"
            ]
          }
        ],
        "parameters": [
          {
            "name": "start",
            "in": "query",
            "required": true,
            "description": "Inclusive lower bound on the lot's creation time, ISO 8601 date or date-time (+07:00 without an offset).",
            "schema": {
              "type": "string"
            },
            "example": "2026-09-01"
          },
          {
            "name": "end",
            "in": "query",
            "required": true,
            "description": "Exclusive upper bound, at most 366 days after start.",
            "schema": {
              "type": "string"
            },
            "example": "2026-10-01"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's next_cursor (X-Next-Cursor); omitted for the first page.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,18}$"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "CSV with a header row (the RecordsExportRow columns, CRLF line ends), then, when a lot's signed device events were cut, one truncation_notice row per cut lot (that record_type, the lot code and device_events_truncated \"true\", every other cell empty), then the rows; a text cell starting with =, +, -, @, a tab or a carriage return gets a leading ' so a spreadsheet never runs it as a formula.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Next-Cursor": {
                "description": "The cursor of the next page; absent on the last page.",
                "schema": {
                  "type": "string",
                  "pattern": "^[0-9]{1,18}$"
                }
              },
              "X-Records-Truncated": {
                "description": "\"true\" when a lot's signed device events were cut at 1,000 (the CSV then starts with a truncation_notice row per cut lot, the JSON has `truncated` true), else \"false\". The console warns on \"true\".",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "record_type,traceability_lot_code,critical_tracking_event,event_date,event_time,record_source,event_id,location,location_description,location_address,location_registration,product_description,quantity,unit_of_measure,area_declared_kg,carton,fruit_count,supplier_name,supplier_organisation,supplier_code,supplier_address,supplier_registration,harvest_date,shipment,container,seal_number,destination,border_gate,consignee_name,consignee_address,consignee_country,consignee_gln,consignee_gacc_record,reference_document_type,reference_document_number,lab_key_custody,lab_market,sample,analyte,result_outcome,result_value,result_unit,limit_kind,limit_value,limit_source,verdict,sealed_digest,sealed_basis,recall_kind,recall_reason,recall_scope,hold_kind,hold_status,device_events_truncated\r\ncte,LO-260928-014,initial_packing,2026-09-29,07:30:00+07:00,system_record,,VN-TGPH-021,Tân Phú,\"Cai Lậy, Tiền Giang\",,durian Ri6,8.6,kg,,C-0928014-0001,3,,,VN-TGOR-0387,\"Ngũ Hiệp, Cai Lậy, Tiền Giang\",,2026-09-27,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,false\r\n"
              }
            }
          },
          "400": {
            "description": "start or end missing or not an ISO 8601 date or date-time, end not after start, a range over 366 days, a bad cursor, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_range": {
                    "value": {
                      "error": "invalid range: at most 366 days",
                      "code": "invalid_range"
                    }
                  },
                  "bad_start": {
                    "value": {
                      "error": "invalid start: an ISO 8601 date or date-time",
                      "code": "invalid_start"
                    }
                  },
                  "bad_cursor": {
                    "value": {
                      "error": "invalid cursor",
                      "code": "invalid_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/records-export.json": {
      "get": {
        "operationId": "getRecordsExportJson",
        "summary": "Records-request export of the tenant's lots in a range (JSON)",
        "description": "The records of the tenant's lots CREATED in [start, end), one page at a time, the same rows as the per-lot export lot by lot (W1-3, #152). `start` and `end` are ISO 8601 dates or date-times (local time, +07:00, without an offset), at most 366 days apart. A page holds at most 50 lots whose cartons together stay within 9,999 (always one lot at least); a lot whose signed device events were cut is flagged by `X-Records-Truncated`, the CSV's truncation_notice row and the JSON's `truncated`; the next page's cursor is `next_cursor` (JSON) or the `X-Next-Cursor` header (CSV, absent on the last page). An audited read (`export.records`: the parsed range, the format, the lot and row counts), downloaded as an attachment, never cached. Allowed for tenant_admin, platform_admin acting for the tenant and auditor; operators and labs are refused; another tenant's lots never appear. An OAuth2 access token (#171) needs the dedicated `records_export` scope, which no other scope implies (403 `role not permitted` otherwise).",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "records_export"
            ]
          }
        ],
        "parameters": [
          {
            "name": "start",
            "in": "query",
            "required": true,
            "description": "Inclusive lower bound on the lot's creation time, ISO 8601 date or date-time (+07:00 without an offset).",
            "schema": {
              "type": "string"
            },
            "example": "2026-09-01"
          },
          {
            "name": "end",
            "in": "query",
            "required": true,
            "description": "Exclusive upper bound, at most 366 days after start.",
            "schema": {
              "type": "string"
            },
            "example": "2026-10-01"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's next_cursor (X-Next-Cursor); omitted for the first page.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{1,18}$"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The export document (RecordsExportRange).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Records-Truncated": {
                "description": "\"true\" when a lot's signed device events were cut at 1,000 (the CSV then starts with a truncation_notice row per cut lot, the JSON has `truncated` true), else \"false\". The console warns on \"true\".",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecordsExportRange"
                },
                "example": {
                  "format": "agritrace-records-export-range/1",
                  "start": "2026-09-01T00:00:00+07:00",
                  "end": "2026-10-01T00:00:00+07:00",
                  "generated_at": "2026-10-02T09:00:00+07:00",
                  "lots": [
                    "LO-260928-014"
                  ],
                  "next_cursor": null,
                  "truncated": false,
                  "columns": [
                    "record_type",
                    "traceability_lot_code",
                    "critical_tracking_event",
                    "event_date",
                    "event_time",
                    "record_source",
                    "event_id",
                    "location",
                    "location_description",
                    "location_address",
                    "location_registration",
                    "product_description",
                    "quantity",
                    "unit_of_measure",
                    "area_declared_kg",
                    "carton",
                    "fruit_count",
                    "supplier_name",
                    "supplier_organisation",
                    "supplier_code",
                    "supplier_address",
                    "supplier_registration",
                    "harvest_date",
                    "shipment",
                    "container",
                    "seal_number",
                    "destination",
                    "border_gate",
                    "consignee_name",
                    "consignee_address",
                    "consignee_country",
                    "consignee_gln",
                    "consignee_gacc_record",
                    "reference_document_type",
                    "reference_document_number",
                    "lab_key_custody",
                    "lab_market",
                    "sample",
                    "analyte",
                    "result_outcome",
                    "result_value",
                    "result_unit",
                    "limit_kind",
                    "limit_value",
                    "limit_source",
                    "verdict",
                    "sealed_digest",
                    "sealed_basis",
                    "recall_kind",
                    "recall_reason",
                    "recall_scope",
                    "hold_kind",
                    "hold_status",
                    "device_events_truncated"
                  ],
                  "rows": [
                    {
                      "record_type": "cte",
                      "traceability_lot_code": "LO-260928-014",
                      "critical_tracking_event": "initial_packing",
                      "event_date": "2026-09-29",
                      "event_time": "07:30:00+07:00",
                      "record_source": "system_record",
                      "event_id": "",
                      "location": "VN-TGPH-021",
                      "location_description": "Tân Phú",
                      "location_address": "Cai Lậy, Tiền Giang",
                      "location_registration": "",
                      "product_description": "durian Ri6",
                      "quantity": 8.6,
                      "unit_of_measure": "kg",
                      "area_declared_kg": "",
                      "carton": "C-0928014-0001",
                      "fruit_count": 3,
                      "supplier_name": "",
                      "supplier_organisation": "",
                      "supplier_code": "VN-TGOR-0387",
                      "supplier_address": "Ngũ Hiệp, Cai Lậy, Tiền Giang",
                      "supplier_registration": "",
                      "harvest_date": "2026-09-27",
                      "shipment": "",
                      "container": "",
                      "seal_number": "",
                      "destination": "",
                      "border_gate": "",
                      "consignee_name": "",
                      "consignee_address": "",
                      "consignee_country": "",
                      "consignee_gln": "",
                      "consignee_gacc_record": "",
                      "reference_document_type": "",
                      "reference_document_number": "",
                      "lab_key_custody": "",
                      "lab_market": "",
                      "sample": "",
                      "analyte": "",
                      "result_outcome": "",
                      "result_value": "",
                      "result_unit": "",
                      "limit_kind": "",
                      "limit_value": "",
                      "limit_source": "",
                      "verdict": "",
                      "sealed_digest": "",
                      "sealed_basis": "",
                      "recall_kind": "",
                      "recall_reason": "",
                      "recall_scope": "",
                      "hold_kind": "",
                      "hold_status": "",
                      "device_events_truncated": "false"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "start or end missing or not an ISO 8601 date or date-time, end not after start, a range over 366 days, a bad cursor, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_range": {
                    "value": {
                      "error": "invalid range: at most 366 days",
                      "code": "invalid_range"
                    }
                  },
                  "bad_start": {
                    "value": {
                      "error": "invalid start: an ISO 8601 date or date-time",
                      "code": "invalid_start"
                    }
                  },
                  "bad_cursor": {
                    "value": {
                      "error": "invalid cursor",
                      "code": "invalid_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/records-export.csv": {
      "get": {
        "operationId": "getLotRecordsExportCsv",
        "summary": "Records-request export of any lot (CSV)",
        "description": "The records of any lot of the tenant for an authority or a buyer, answered within 24 hours by one request (W1-3, #152; RecordsExport and RecordsExportRow describe the rows and every column): the critical tracking events, the registry facts frozen at seal, every lab result, the recall when any and the lot's open or escalated holds, with the supplier (one step back) on every row and the shipment (one step forward) on the shipping rows. Bounded (at most 9,999 cartons, 1,000 signed device events, 384 lab results); a cut lot is flagged by `X-Records-Truncated`, the CSV's truncation_notice row and the JSON's `truncated`. An audited read (`export.records`: the format and the row count), downloaded as an attachment (`Content-Disposition`), never cached. Allowed for tenant_admin, platform_admin acting for the tenant and auditor; operators and labs are refused; another tenant's lot answers like a missing one. An OAuth2 access token (#171) needs the dedicated `records_export` scope, which no other scope implies (403 `role not permitted` otherwise).",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "records_export"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "CSV with a header row (the RecordsExportRow columns, CRLF line ends), then, when a lot's signed device events were cut, one truncation_notice row per cut lot (that record_type, the lot code and device_events_truncated \"true\", every other cell empty), then the rows; a text cell starting with =, +, -, @, a tab or a carriage return gets a leading ' so a spreadsheet never runs it as a formula.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Records-Truncated": {
                "description": "\"true\" when a lot's signed device events were cut at 1,000 (the CSV then starts with a truncation_notice row per cut lot, the JSON has `truncated` true), else \"false\". The console warns on \"true\".",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "record_type,traceability_lot_code,critical_tracking_event,event_date,event_time,record_source,event_id,location,location_description,location_address,location_registration,product_description,quantity,unit_of_measure,area_declared_kg,carton,fruit_count,supplier_name,supplier_organisation,supplier_code,supplier_address,supplier_registration,harvest_date,shipment,container,seal_number,destination,border_gate,consignee_name,consignee_address,consignee_country,consignee_gln,consignee_gacc_record,reference_document_type,reference_document_number,lab_key_custody,lab_market,sample,analyte,result_outcome,result_value,result_unit,limit_kind,limit_value,limit_source,verdict,sealed_digest,sealed_basis,recall_kind,recall_reason,recall_scope,hold_kind,hold_status,device_events_truncated\r\ncte,LO-260928-014,initial_packing,2026-09-29,07:30:00+07:00,system_record,,VN-TGPH-021,Tân Phú,\"Cai Lậy, Tiền Giang\",,durian Ri6,8.6,kg,,C-0928014-0001,3,,,VN-TGOR-0387,\"Ngũ Hiệp, Cai Lậy, Tiền Giang\",,2026-09-27,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,false\r\n"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/records-export.json": {
      "get": {
        "operationId": "getLotRecordsExportJson",
        "summary": "Records-request export of any lot (JSON)",
        "description": "The records of any lot of the tenant for an authority or a buyer, answered within 24 hours by one request (W1-3, #152; RecordsExport and RecordsExportRow describe the rows and every column): the critical tracking events, the registry facts frozen at seal, every lab result, the recall when any and the lot's open or escalated holds, with the supplier (one step back) on every row and the shipment (one step forward) on the shipping rows. Bounded (at most 9,999 cartons, 1,000 signed device events, 384 lab results); a cut lot is flagged by `X-Records-Truncated`, the CSV's truncation_notice row and the JSON's `truncated`. An audited read (`export.records`: the format and the row count), downloaded as an attachment (`Content-Disposition`), never cached. Allowed for tenant_admin, platform_admin acting for the tenant and auditor; operators and labs are refused; another tenant's lot answers like a missing one. An OAuth2 access token (#171) needs the dedicated `records_export` scope, which no other scope implies (403 `role not permitted` otherwise).",
        "tags": [
          "traceability"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "records_export"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The export document (RecordsExport).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "X-Records-Truncated": {
                "description": "\"true\" when a lot's signed device events were cut at 1,000 (the CSV then starts with a truncation_notice row per cut lot, the JSON has `truncated` true), else \"false\". The console warns on \"true\".",
                "schema": {
                  "type": "string",
                  "enum": [
                    "true",
                    "false"
                  ]
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecordsExport"
                },
                "example": {
                  "format": "agritrace-records-export/1",
                  "lot": "LO-260928-014",
                  "status": "packed",
                  "generated_at": "2026-10-02T09:00:00+07:00",
                  "truncated": false,
                  "sealed_record": null,
                  "columns": [
                    "record_type",
                    "traceability_lot_code",
                    "critical_tracking_event",
                    "event_date",
                    "event_time",
                    "record_source",
                    "event_id",
                    "location",
                    "location_description",
                    "location_address",
                    "location_registration",
                    "product_description",
                    "quantity",
                    "unit_of_measure",
                    "area_declared_kg",
                    "carton",
                    "fruit_count",
                    "supplier_name",
                    "supplier_organisation",
                    "supplier_code",
                    "supplier_address",
                    "supplier_registration",
                    "harvest_date",
                    "shipment",
                    "container",
                    "seal_number",
                    "destination",
                    "border_gate",
                    "consignee_name",
                    "consignee_address",
                    "consignee_country",
                    "consignee_gln",
                    "consignee_gacc_record",
                    "reference_document_type",
                    "reference_document_number",
                    "lab_key_custody",
                    "lab_market",
                    "sample",
                    "analyte",
                    "result_outcome",
                    "result_value",
                    "result_unit",
                    "limit_kind",
                    "limit_value",
                    "limit_source",
                    "verdict",
                    "sealed_digest",
                    "sealed_basis",
                    "recall_kind",
                    "recall_reason",
                    "recall_scope",
                    "hold_kind",
                    "hold_status",
                    "device_events_truncated"
                  ],
                  "rows": [
                    {
                      "record_type": "cte",
                      "traceability_lot_code": "LO-260928-014",
                      "critical_tracking_event": "initial_packing",
                      "event_date": "2026-09-29",
                      "event_time": "07:30:00+07:00",
                      "record_source": "system_record",
                      "event_id": "",
                      "location": "VN-TGPH-021",
                      "location_description": "Tân Phú",
                      "location_address": "Cai Lậy, Tiền Giang",
                      "location_registration": "",
                      "product_description": "durian Ri6",
                      "quantity": 8.6,
                      "unit_of_measure": "kg",
                      "area_declared_kg": "",
                      "carton": "C-0928014-0001",
                      "fruit_count": 3,
                      "supplier_name": "",
                      "supplier_organisation": "",
                      "supplier_code": "VN-TGOR-0387",
                      "supplier_address": "Ngũ Hiệp, Cai Lậy, Tiền Giang",
                      "supplier_registration": "",
                      "harvest_date": "2026-09-27",
                      "shipment": "",
                      "container": "",
                      "seal_number": "",
                      "destination": "",
                      "border_gate": "",
                      "consignee_name": "",
                      "consignee_address": "",
                      "consignee_country": "",
                      "consignee_gln": "",
                      "consignee_gacc_record": "",
                      "reference_document_type": "",
                      "reference_document_number": "",
                      "lab_key_custody": "",
                      "lab_market": "",
                      "sample": "",
                      "analyte": "",
                      "result_outcome": "",
                      "result_value": "",
                      "result_unit": "",
                      "limit_kind": "",
                      "limit_value": "",
                      "limit_source": "",
                      "verdict": "",
                      "sealed_digest": "",
                      "sealed_basis": "",
                      "recall_kind": "",
                      "recall_reason": "",
                      "recall_scope": "",
                      "hold_kind": "",
                      "hold_status": "",
                      "device_events_truncated": "false"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, platform_admin and auditor only) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/metrics": {
      "get": {
        "operationId": "getMetrics",
        "summary": "Request, database and scan metrics in the Prometheus text format",
        "description": "This process's metrics in the Prometheus text exposition format (version 0.0.4), for a platform admin's signed-in session, or for a scraper holding a platform_admin API token, which only CropPath's operators create (on the server, never from the console or the API): per-route request latency histograms (`agritrace_http_request_duration_seconds`), SQL statements per request (`agritrace_http_request_db_statements`) and the time a request waited for the database (`agritrace_http_request_db_wait_seconds`: the SQLite connection lock, or a free pooled PostgreSQL connection), each by method, route pattern (or `unmatched`) and status; and public scans logged and deduplicated (`agritrace_scans_total`, scans per second is its rate). #81: also the ingest outcomes of this process (`agritrace_ingest_messages_total` by result: accepted, quarantined, duplicate, rejected; `agritrace_ingest_reasons_total` by result and reason code, one per reason of a quarantined or rejected message), the server-sent event streams open on this server and its cap (`agritrace_sse_streams_open`, `agritrace_sse_streams_max`), the accepted events not yet delivered per outbound target (`agritrace_outbound_backlog`, read from the database, so every process reports the same number; 0 for a configured target with nothing waiting), and what the sampled browsers reported to `postUiTelemetry` (`agritrace_ui_lcp_seconds`, `agritrace_ui_inp_seconds` and `agritrace_ui_cls` histograms, `agritrace_ui_beacons_total` and `agritrace_ui_errors_total`, by page kind). #134: also the companies' quotas and their use: `agritrace_tenant_quota` by company (`*` for the default of every company not named in AGRITRACE_TENANT_QUOTAS) and quota (api_per_minute, api_per_day, ingest_per_second, ingest_burst), `agritrace_tenant_api_calls_today` and `agritrace_tenant_api_refused_total` (by quota: per_minute, per_day) per company, and per company the messages waiting in the ingest backlog (`agritrace_tenant_ingest_backlog`), kept there (`agritrace_tenant_ingest_deferred_total`), stored from it (`agritrace_tenant_ingest_drained_total`), kept while the backlog was over its company's disk budget (`agritrace_tenant_ingest_backlog_full_total`; such messages are still kept and stored at the quota) and refused over HTTP (`agritrace_tenant_ingest_refused_total`), the backlog's bytes (`agritrace_tenant_ingest_backlog_bytes`), and the HTTP messages without a client certificate, or with one of no registered device or gateway, refused by their client address's bucket (`agritrace_ingest_unidentified_refused_total`, no company label); the company label is a company id, bounded by the number of companies. Public latency is `agritrace_http_request_duration_seconds` of the `/v1/public/...` routes. Label values are bounded (no record IDs, addresses or tokens). Allowed for platform_admin only. Not audited (a read). `no-store`.",
        "tags": [
          "ops"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "responses": {
          "200": {
            "description": "The metrics.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "text/plain; version=0.0.4; charset=utf-8": {
                "schema": {
                  "type": "string"
                },
                "example": "# HELP agritrace_http_request_duration_seconds Time from the parsed request to the response sent, by route.\n# TYPE agritrace_http_request_duration_seconds histogram\nagritrace_http_request_duration_seconds_bucket{method=\"GET\",route=\"/v1/public/fruits/{publicId}\",status=\"200\",le=\"0.025\"} 41\nagritrace_http_request_duration_seconds_bucket{method=\"GET\",route=\"/v1/public/fruits/{publicId}\",status=\"200\",le=\"+Inf\"} 42\nagritrace_http_request_duration_seconds_sum{method=\"GET\",route=\"/v1/public/fruits/{publicId}\",status=\"200\"} 0.61\nagritrace_http_request_duration_seconds_count{method=\"GET\",route=\"/v1/public/fruits/{publicId}\",status=\"200\"} 42\n# HELP agritrace_scans_total Public fruit scans the web server's reads logged (new) or found again within the dedupe window (deduplicated); rate() gives scans per second.\n# TYPE agritrace_scans_total counter\nagritrace_scans_total{result=\"deduplicated\"} 3\nagritrace_scans_total{result=\"logged\"} 39\n"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "This process's metrics in the Prometheus text exposition format (version 0.0.4), for a platform admin's signed-in session, or for a scraper holding a platform_admin API token, which only CropPath's operators create (on the server, never from the console or the API): per-route request latency histograms (`agritrace_http_request_duration_seconds`), SQL statements per request (`agritrace_http_request_db_statements`) and the time a request waited for the database (`agritrace_http_request_db_wait_seconds`: the SQLite connection lock, or a free pooled PostgreSQL connection), each by method, route pattern (or `unmatched`) and status; and public scans logged and deduplicated (`agritrace_scans_total`, scans per second is its rate). Label values are bounded (no IDs, addresses or tokens). Allowed for platform_admin only. Not audited (a read). `no-store`."
      }
    },
    "/v1/telemetry/ui": {
      "post": {
        "operationId": "postUiTelemetry",
        "summary": "Report a page's web vitals and uncaught errors (browser beacon)",
        "description": "Anonymous (#81): the beacon a sampled page of the web app sends once when it is hidden or left (`navigator.sendBeacon`). A request carrying a session, token or cookie is treated like an anonymous one. In order: the /v1/public/* bucket and the telemetry bucket (bursts of 10, then 2 beacons a minute per client), keyed like the public routes; a Content-Length of 1 to 7 plain digits (400 `invalid_beacon` when it is missing or anything else, a chunked body included, before the body is read); a body of at most 1024 bytes (413 otherwise, before it is read); the body (UiTelemetryBeacon, strictly: an unknown field, a page kind outside the list, a measure that is not a number in range, more than 5 errors or nothing to report is 400 `invalid_beacon`). The beacon only adds to this process's counters and histograms, rendered by `getMetrics`; nothing is stored, logged or echoed, and its request log line names no peer address. It carries no personal data: a page kind, never the URL or an id; an error's kind and constructor name (names outside the standard ones count as `other`), never its message or stack. Not audited (AUDIT_EXEMPT: it changes no record, and an anonymous route must not append to the audit log). Every answer is `no-store`. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "ops"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UiTelemetryBeacon"
              },
              "example": {
                "page": "fruit",
                "lcp_ms": 1834.2,
                "cls": 0.02,
                "inp_ms": 96,
                "errors": [
                  {
                    "kind": "error",
                    "name": "TypeError"
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "204": {
            "description": "The beacon was counted.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "400": {
            "description": "A Content-Length that is missing or is not 1 to 7 plain digits (a chunked body included; `invalid_beacon`, the connection is closed, the body is never read), invalid JSON, a body that does not fit UiTelemetryBeacon, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_beacon": {
                    "value": {
                      "error": "invalid beacon: unknown page",
                      "code": "invalid_beacon"
                    }
                  },
                  "bad_content_length": {
                    "value": {
                      "error": "invalid beacon: bad content length",
                      "code": "invalid_beacon"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "description": "The body is over 1024 bytes; the connection is closed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "body too large",
                  "code": "body_too_large"
                }
              }
            }
          },
          "429": {
            "description": "The client's public or telemetry bucket is empty: retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              },
              "Retry-After": {
                "description": "Seconds until a token is back.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/registry-lists": {
      "get": {
        "operationId": "listRegistryLists",
        "summary": "Imported growing-area and packing-house code lists",
        "description": "Every import of a published PUC/PHC code list (#150), newest first, one page (`limit`, default 50, at most 200; `cursor`). `current`: not superseded by a later import of the same kind, market and crop; `stale`: current and older than `max_age_days` (AGRITRACE_REGISTRY_LIST_MAX_AGE_DAYS, default 30), so no registration step is Cross-checked against it; `crops`: the crops an import may name (AGRITRACE_REGISTRY_CROPS, by default the D7 crops). Platform data, read across tenants. Allowed for platform_admin only. Not audited (a read).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjN9"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of imports.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistryListPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "kind": "puc",
                      "market": "CN",
                      "crop": "durian",
                      "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
                      "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
                      "source_media_type": "application/pdf",
                      "published_on": "2026-09-25",
                      "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
                      "file_sha256": "9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f",
                      "file_size": 48213,
                      "entry_count": 812,
                      "imported_at": 1790000000.5,
                      "imported_by": "admin@croppath.example",
                      "superseded_by": null,
                      "superseded_at": null,
                      "retired_by": null,
                      "retire_reason": null,
                      "current": true,
                      "stale": false
                    }
                  ],
                  "max_age_days": 30,
                  "crops": [
                    "coconut",
                    "dragon_fruit",
                    "durian",
                    "jackfruit",
                    "mango"
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "importRegistryList",
        "summary": "Import a published code list",
        "description": "A platform admin imports the PUC (growing areas) or PHC (packing houses) code list the authority published for a destination market and crop, converted to CSV (UTF-8; columns code (required), status (active, suspended or revoked; empty: active), holder, province, district, commune, crop, area_ha, valid_from, valid_to (YYYY-MM-DD or DD/MM/YYYY); at most 737,280 bytes and 20,000 rows), sent as base64. The file is stored byte for byte with its SHA-256 as evidence, beside the file the authority published (`source_sha256`, required: the SHA-256 of an original uploaded first with PUT /v1/registry-sources/{sha256}), and the import supersedes the current list of the same kind, market and crop. The crop must be one of the platform's crops, and an import that would make more than 200 lists current is refused (400) rather than letting the oldest drop out of the check. A bad file is refused whole with the first bad rows named. Audited (`registry_list.import`, in the same transaction); the audit queues every lot whose growing area or facility carries a code for a trust recompute (the registration step). Allowed for platform_admin only.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RegistryListImport"
              },
              "example": {
                "kind": "puc",
                "market": "CN",
                "crop": "durian",
                "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
                "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
                "published_on": "2026-09-25",
                "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
                "file_base64": "Y29kZSxzdGF0dXMKVk4tRExPUi0wMTAxLGFjdGl2ZQo="
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The import, now the current list of its kind, market and crop.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistryList"
                },
                "example": {
                  "id": 3,
                  "kind": "puc",
                  "market": "CN",
                  "crop": "durian",
                  "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
                  "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
                  "source_media_type": "application/pdf",
                  "published_on": "2026-09-25",
                  "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
                  "file_sha256": "9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f",
                  "file_size": 48213,
                  "entry_count": 812,
                  "imported_at": 1790000000.5,
                  "imported_by": "admin@croppath.example",
                  "superseded_by": null,
                  "superseded_at": null,
                  "retired_by": null,
                  "retire_reason": null,
                  "current": true,
                  "stale": false,
                  "superseded": 2
                }
              }
            }
          },
          "400": {
            "description": "A bad file or detail, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "file": {
                    "value": {
                      "error": "invalid file: row 12: invalid status: active, suspended, revoked",
                      "code": "invalid_file"
                    }
                  },
                  "base64": {
                    "value": {
                      "error": "invalid file_base64: the list file, base64-encoded",
                      "code": "invalid_file_base64"
                    }
                  },
                  "kind": {
                    "value": {
                      "error": "invalid kind: puc (growing areas) or phc (packing houses)",
                      "code": "invalid_kind"
                    }
                  },
                  "source": {
                    "value": {
                      "error": "invalid source_sha256: no stored original file has this SHA-256; upload the file the authority published first (PUT /v1/registry-sources/{sha256})",
                      "code": "invalid_source_sha256"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ]
      }
    },
    "/v1/registry-lists/{id}": {
      "get": {
        "operationId": "getRegistryList",
        "summary": "One imported code list",
        "description": "One import with its entry counts by status. Platform data, read across tenants. Allowed for platform_admin only. Not audited (a read).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The import's id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "responses": {
          "200": {
            "description": "The import.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistryListDetail"
                },
                "example": {
                  "id": 3,
                  "kind": "puc",
                  "market": "CN",
                  "crop": "durian",
                  "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
                  "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
                  "source_media_type": "application/pdf",
                  "published_on": "2026-09-25",
                  "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
                  "file_sha256": "9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f",
                  "file_size": 48213,
                  "entry_count": 812,
                  "imported_at": 1790000000.5,
                  "imported_by": "admin@croppath.example",
                  "superseded_by": null,
                  "superseded_at": null,
                  "retired_by": null,
                  "retire_reason": null,
                  "current": true,
                  "stale": false,
                  "status_counts": {
                    "active": 805,
                    "suspended": 6,
                    "revoked": 1
                  },
                  "max_age_days": 30
                }
              }
            }
          },
          "404": {
            "description": "No such import (anything that is not an id answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: registry_lists",
                  "code": "not_found"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/registry-lists/{id}/retire": {
      "post": {
        "operationId": "retireRegistryList",
        "summary": "Retire an imported code list",
        "description": "#150 re-review (MO decision 3): a platform admin retires a current code list, for example one imported for the wrong kind, market or crop, with a reason. It stops being current at once: its codes match nothing, it leaves the current-list cap, and no successor is named (`superseded_at` set, `superseded_by` null). The list, its stored file and the authority's original file stay as evidence (no DELETE). Audited (`registry_list.retire`, in the same transaction, with the reason); the audit queues every lot whose growing area or facility carries a code for a trust recompute. Allowed for platform_admin only.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The import's id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RegistryListRetire"
              },
              "example": {
                "reason": "imported for the wrong crop"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The list, retired.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistryList"
                },
                "example": {
                  "id": 3,
                  "kind": "puc",
                  "market": "CN",
                  "crop": "durian",
                  "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
                  "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
                  "source_media_type": "application/pdf",
                  "published_on": "2026-09-25",
                  "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
                  "file_sha256": "9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f",
                  "file_size": 48213,
                  "entry_count": 812,
                  "imported_at": 1790000000.5,
                  "imported_by": "admin@croppath.example",
                  "superseded_by": null,
                  "superseded_at": 1790003600.5,
                  "retired_by": "admin@croppath.example",
                  "retire_reason": "imported for the wrong crop",
                  "current": false,
                  "stale": false
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a missing, blank, multi-line or longer than 200 characters reason, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: 1 to 200 characters on one line",
                      "code": "invalid_reason"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: kind",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such import (anything that is not an id answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: registry_lists",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The list is not current: a later import superseded it, or it was retired already. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "list_is_not_current": {
                    "value": {
                      "error": "list is not current: superseded or retired already",
                      "code": "list_is_not_current"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/registry-lists/{id}/entries": {
      "get": {
        "operationId": "listRegistryListEntries",
        "summary": "The entries of an imported code list",
        "description": "One page of the import's entries by normalised code (`limit`, default 50, at most 200; `cursor`). Platform data, read across tenants. Allowed for platform_admin only. Not audited (a read).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The import's id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IlZOLURMT1ItMDEwMSJ9"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of entries.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistryListEntryPage"
                },
                "example": {
                  "items": [
                    {
                      "code": "VN-DLOR-0101",
                      "code_raw": "VN-DLOR-0101",
                      "status": "active",
                      "holder": "HTX Krông Pắc",
                      "province": "Đắk Lắk",
                      "district": "Krông Pắc",
                      "commune": "Ea Kly",
                      "area_ha": 12.5,
                      "valid_from": null,
                      "valid_to": null
                    }
                  ],
                  "next_cursor": "eyJhZnRlciI6IlZOLURMT1ItMDEwMSJ9"
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such import (anything that is not an id answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: registry_lists",
                  "code": "not_found"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/registry-lists/{id}/file": {
      "get": {
        "operationId": "getRegistryListFile",
        "summary": "The stored file of an imported code list",
        "description": "The file as imported, byte for byte: its SHA-256 is the import's `file_sha256`. A download (`registry-list-<id>.csv`), `Cache-Control: no-store`. Platform data, read across tenants. Allowed for platform_admin only. Not audited (a read).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The import's id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "responses": {
          "200": {
            "description": "The CSV file.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"registry-list-<id>.csv\"`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                },
                "example": "code,status\nVN-DLOR-0101,active\n"
              }
            }
          },
          "404": {
            "description": "No such import (anything that is not an id answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: registry_lists",
                  "code": "not_found"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/registry-lists/{id}/source": {
      "get": {
        "operationId": "getRegistryListSource",
        "summary": "The authority's original file of an imported code list",
        "description": "The file the authority published, as the platform admin uploaded it before the import (#150 re-review), byte for byte: its SHA-256 is the import's `source_sha256`. Served with its stored media type (PDF, XLSX, XLS or CSV) as a download (`registry-source-<id>.<pdf|xlsx|xls|csv>`), `Cache-Control: no-store`, `X-Content-Type-Options: nosniff` and a sandboxing Content-Security-Policy. Platform data, read across tenants. Allowed for platform_admin only. Not audited (a read).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The import's id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "responses": {
          "200": {
            "description": "The original file.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"registry-source-<id>.<ext>\"`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/pdf": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "application/pdf"
                },
                "example": "%PDF-1.7 ... (binary PDF bytes)"
              },
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                },
                "example": "(binary XLSX bytes, starting 50 4B 03 04)"
              },
              "application/vnd.ms-excel": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "application/vnd.ms-excel"
                },
                "example": "(binary XLS bytes, starting D0 CF 11 E0 A1 B1 1A E1)"
              },
              "text/csv": {
                "schema": {
                  "type": "string",
                  "contentMediaType": "text/csv"
                },
                "example": "Mã số,Tên chủ sở hữu\nVN-DLOR-0101,HTX Krông Pắc\n"
              }
            }
          },
          "404": {
            "description": "No such import, or its original file is missing from the store (anything that is not an id answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: registry_lists",
                  "code": "not_found"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/registry-matches": {
      "get": {
        "operationId": "listRegistryMatches",
        "summary": "Registered codes checked against the current code lists",
        "description": "The growing areas' PUC (`kind=puc`) or the facilities' PHC (`kind=phc`) codes of every tenant, one page by area or facility code (`limit`, default 50, at most 200; `cursor`), each with its check against the current lists of the kind (any market): `matched` (on the list of its crop, active and within its dates; for a facility, any crop's list), `suspended`, `revoked`, `expired`, `mismatch` (only on another crop's list), `not_found`, `no_list` (no current list of its crop) or `no_code`; `stale` when the list is older than `max_age_days`. Platform data, read across tenants. Allowed for platform_admin only. Not audited (a read).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "kind",
            "in": "query",
            "required": true,
            "description": "puc or phc.",
            "schema": {
              "type": "string",
              "enum": [
                "puc",
                "phc"
              ]
            },
            "example": "puc"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6IlZOLVRHT1ItMDM4NyJ9"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of registered codes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistryMatchPage"
                },
                "example": {
                  "items": [
                    {
                      "code": "VN-TGOR-0387",
                      "tenant": "coop-dl",
                      "name": "Vườn Ngũ Hiệp",
                      "crop": "durian",
                      "registered_code": "VN-TGOR-0387-PUC",
                      "normalized_code": "VN-TGOR-0387-PUC",
                      "result": "matched",
                      "stale": false,
                      "list_id": 3,
                      "list_crop": "durian"
                    }
                  ],
                  "max_age_days": 30,
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `kind`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "kind": {
                    "value": {
                      "error": "invalid kind: puc or phc",
                      "code": "invalid_kind"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/registry-sources/{sha256}": {
      "put": {
        "operationId": "uploadRegistrySource",
        "summary": "Upload the authority's original file of a code list",
        "description": "#150 re-review (MO decision 2): before importing a published code list, a platform admin uploads the file the authority published (its PDF, XLSX, XLS or CSV) as it was downloaded. The body must hash to `sha256` (the server computes it; a mismatch is 422 and nothing is stored), be at most 1 MiB, have one of these Content-Types (parameters ignored) and that type's signature (a CSV: no NUL byte). The file is kept in the content-addressed blob store for platform admins only (GET /v1/registry-lists/{id}/source); an import then cites it as `source_sha256`. An original already stored: 200 without reading the body. Audited (`registry_source.upload`: the hash, media type and size, never the bytes). Allowed for platform_admin only.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "sha256",
            "in": "path",
            "required": true,
            "description": "SHA-256 of the original file: exactly 64 lowercase hex characters (anything else is 400 before any lookup).",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            },
            "example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/pdf": {
              "schema": {
                "type": "string",
                "contentMediaType": "application/pdf"
              },
              "example": "%PDF-1.7 ... (binary PDF bytes)"
            },
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
              "schema": {
                "type": "string",
                "contentMediaType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              },
              "example": "(binary XLSX bytes, starting 50 4B 03 04)"
            },
            "application/vnd.ms-excel": {
              "schema": {
                "type": "string",
                "contentMediaType": "application/vnd.ms-excel"
              },
              "example": "(binary XLS bytes, starting D0 CF 11 E0 A1 B1 1A E1)"
            },
            "text/csv": {
              "schema": {
                "type": "string",
                "contentMediaType": "text/csv"
              },
              "example": "Mã số,Tên chủ sở hữu\nVN-DLOR-0101,HTX Krông Pắc\n"
            }
          }
        },
        "responses": {
          "200": {
            "description": "This original is already stored; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistrySourceStored"
                },
                "example": {
                  "sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
                  "media_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                  "size": 182044
                }
              }
            }
          },
          "201": {
            "description": "Stored; an import may now cite it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RegistrySourceStored"
                },
                "example": {
                  "sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
                  "media_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                  "size": 182044
                }
              }
            }
          },
          "400": {
            "description": "Malformed sha256 in the path, a missing or malformed Content-Length, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_hash": {
                    "value": {
                      "error": "invalid hash",
                      "code": "invalid_hash"
                    }
                  },
                  "bad_content_length": {
                    "value": {
                      "error": "bad content length",
                      "code": "bad_content_length"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin_not_allowed": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "415": {
            "description": "Media type outside the allowlist (application/pdf, the XLSX and XLS spreadsheet types, text/csv), or bytes that do not carry that type's signature.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unsupported_media_type": {
                    "value": {
                      "error": "unsupported media type",
                      "code": "unsupported_media_type"
                    }
                  },
                  "content_does_not_match_the_media_type": {
                    "value": {
                      "error": "content does not match the media type",
                      "code": "content_does_not_match_the_media_type"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "The body does not hash to `sha256`; nothing is stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "hash mismatch",
                  "code": "hash_mismatch"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/approvals": {
      "get": {
        "operationId": "listLabApprovals",
        "summary": "A lab's market approvals",
        "description": "#154: every market approval of the lab (at most 100, one page), each with whether it is in force today. Allowed for platform_admin (every lab) and for a lab user signed in with a session (its own lab only; another lab answers 404 like a missing one). A lab principal without a lab (an API token) is refused 403. Not audited (a read).",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          }
        ],
        "responses": {
          "200": {
            "description": "The lab's approvals.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabApprovalList"
                },
                "example": {
                  "items": [
                    {
                      "id": 7,
                      "lab": "LAB-VN-118",
                      "market": "CN",
                      "approving_body": "Plant Protection Department (MAE)",
                      "reference": "List of approved labs, 2026-08-07, No. 17",
                      "analytes": [
                        "auramine_o",
                        "cadmium"
                      ],
                      "valid_from": "2026-08-07",
                      "valid_to": "2027-08-06",
                      "source_url": "https://example.org/approved-labs-2026",
                      "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
                      "status": "active",
                      "in_force": true,
                      "created_at": 1790000000.5,
                      "created_by": "admin@platform.example",
                      "updated_at": 1790000000.5,
                      "updated_by": "admin@platform.example"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab, or a lab outside the caller's scope (a lab user's other labs).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createLabApproval",
        "summary": "Record a lab's market approval",
        "description": "#154: records an active approval of the lab for a destination market (approving body, reference, analytes covered, validity, optional source URL and evidence SHA-256). Every lot the lab reported on is queued for a trust recompute in the same transaction: a result counts toward Lab-verified for the report's market only when an approval valid on the signed date lists the analyte. Audited (`lab_approval.create`). Allowed for platform_admin.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabApprovalCreate"
              },
              "example": {
                "market": "CN",
                "approving_body": "Plant Protection Department (MAE)",
                "reference": "List of approved labs, 2026-08-07, No. 17",
                "analytes": [
                  "auramine_o",
                  "cadmium"
                ],
                "valid_from": "2026-08-07",
                "valid_to": "2027-08-06",
                "source_url": "https://example.org/approved-labs-2026",
                "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The approval recorded.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabApproval"
                },
                "example": {
                  "id": 7,
                  "lab": "LAB-VN-118",
                  "market": "CN",
                  "approving_body": "Plant Protection Department (MAE)",
                  "reference": "List of approved labs, 2026-08-07, No. 17",
                  "analytes": [
                    "auramine_o",
                    "cadmium"
                  ],
                  "valid_from": "2026-08-07",
                  "valid_to": "2027-08-06",
                  "source_url": "https://example.org/approved-labs-2026",
                  "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
                  "status": "active",
                  "in_force": true,
                  "created_at": 1790000000.5,
                  "created_by": "admin@platform.example",
                  "updated_at": 1790000000.5,
                  "updated_by": "admin@platform.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad value, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: status",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_analytes": {
                    "value": {
                      "error": "invalid analytes: 1 to 32 distinct analyte codes (a lower-case letter, then lower-case letters, digits or '_'), e.g. cadmium",
                      "code": "invalid_analytes"
                    }
                  },
                  "invalid_valid_to": {
                    "value": {
                      "error": "invalid valid_to: on or after valid_from",
                      "code": "invalid_valid_to"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab, or a lab outside the caller's scope (a lab user's other labs).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LAB-VN-118",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The lab holds the maximum number of approvals (100). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "too_many_approvals": {
                    "value": {
                      "error": "too many approvals: a lab holds at most 100",
                      "code": "too_many_approvals"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/approvals/{id}": {
      "patch": {
        "operationId": "updateLabApproval",
        "summary": "Correct or withdraw a lab's market approval",
        "description": "#154: changes any editable field of an approval of the lab (not its market); `status` `withdrawn` withdraws it (nothing is deleted). Every lot the lab reported on is queued for a trust recompute in the same transaction. Audited (`lab_approval.update`, with the prior state). Allowed for platform_admin.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Approval id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "7"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LabApprovalUpdate"
              },
              "example": {
                "status": "withdrawn"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The approval after the change.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabApproval"
                },
                "example": {
                  "id": 7,
                  "lab": "LAB-VN-118",
                  "market": "CN",
                  "approving_body": "Plant Protection Department (MAE)",
                  "reference": "List of approved labs, 2026-08-07, No. 17",
                  "analytes": [
                    "auramine_o",
                    "cadmium"
                  ],
                  "valid_from": "2026-08-07",
                  "valid_to": "2027-08-06",
                  "source_url": "https://example.org/approved-labs-2026",
                  "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
                  "status": "withdrawn",
                  "in_force": false,
                  "created_at": 1790000000.5,
                  "created_by": "admin@platform.example",
                  "updated_at": 1790000000.5,
                  "updated_by": "admin@platform.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, nothing to update, an unknown field, a bad value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "nothing_to_update": {
                    "value": {
                      "error": "nothing to update",
                      "code": "nothing_to_update"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: market",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_status": {
                    "value": {
                      "error": "invalid status: active or withdrawn",
                      "code": "invalid_status"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab or approval, an approval of another lab, or a lab outside the caller's scope.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/companies": {
      "get": {
        "operationId": "listLabCompanies",
        "summary": "The companies a lab serves",
        "description": "#278. The companies whose lots a sampling may draw the lab for (at most 500, by company id): a lot's lab is drawn only among the labs in force, with an active key, that serve the lot's company. A lab no company is linked to serves none. Not audited (a read). Allowed for platform_admin only: no company and no lab user reads which companies a lab serves. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the platform admin console's lab page.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          }
        ],
        "responses": {
          "200": {
            "description": "The companies the lab serves.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabCompanyList"
                },
                "example": {
                  "items": [
                    {
                      "lab": "LAB-VN-118",
                      "tenant": "coop-dl",
                      "name": "HTX Nông nghiệp Đồng Lợi",
                      "linked_at": 1790000000.5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only: no company role and no lab user reads which companies a lab serves) or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: labs",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/labs/{code}/companies/{tenant}": {
      "put": {
        "operationId": "linkLabCompany",
        "summary": "Let a lab serve a company",
        "description": "#278. From now on the company's lots may be drawn the lab (when it is in force with an active key and, for a market whose approved-lab list is imported, approved for it). Takes no body. Linking a company the lab already serves changes nothing (200). The company record of the lab logins (`croppath-labs`) has no lots and is refused (409 `lab_logins_company`); a lab serves at most 500 companies (409 `too_many_companies`). Audited (`lab_company.link`, entity `<lab>/<company>`, with `linked` `new` or `already`). Allowed for platform_admin only. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the platform admin console's lab page.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "name": "tenant",
            "in": "path",
            "required": true,
            "description": "Company id (tenant), e.g. coop-dl.",
            "schema": {
              "type": "string"
            },
            "example": "coop-dl"
          }
        ],
        "responses": {
          "200": {
            "description": "The lab already served the company; nothing changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabCompany"
                },
                "example": {
                  "lab": "LAB-VN-118",
                  "tenant": "coop-dl",
                  "name": "HTX Nông nghiệp Đồng Lợi",
                  "linked_at": 1790000000.5
                }
              }
            }
          },
          "201": {
            "description": "The new link.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabCompany"
                },
                "example": {
                  "lab": "LAB-VN-118",
                  "tenant": "coop-dl",
                  "name": "HTX Nông nghiệp Đồng Lợi",
                  "linked_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "A body (linking takes no input) or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: linking takes no input",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab or company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lab": {
                    "value": {
                      "error": "not found: labs",
                      "code": "not_found"
                    }
                  },
                  "company": {
                    "value": {
                      "error": "not found: tenants",
                      "code": "not_found"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The lab logins' company record, or the lab serves the maximum number of companies (500).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lab_logins_company": {
                    "value": {
                      "error": "lab logins company: it holds the labs' logins and has no lots to sample",
                      "code": "lab_logins_company"
                    }
                  },
                  "too_many_companies": {
                    "value": {
                      "error": "too many companies: a lab serves at most 500",
                      "code": "too_many_companies"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "delete": {
        "operationId": "unlinkLabCompany",
        "summary": "Stop a lab serving a company",
        "description": "#278. The company's later lots are never drawn the lab; the samplings already assigned to it stay as they are. A sampling of the company in progress commits first (the link is read FOR SHARE). Audited (`lab_company.unlink`, entity `<lab>/<company>`, with the prior link). Allowed for platform_admin only. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the platform admin console's lab page.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Lab code, e.g. LAB-VN-118.",
            "schema": {
              "type": "string"
            },
            "example": "LAB-VN-118"
          },
          {
            "name": "tenant",
            "in": "path",
            "required": true,
            "description": "Company id (tenant), e.g. coop-dl.",
            "schema": {
              "type": "string"
            },
            "example": "coop-dl"
          }
        ],
        "responses": {
          "204": {
            "description": "Removed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lab, or the lab does not serve the company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lab": {
                    "value": {
                      "error": "not found: labs",
                      "code": "not_found"
                    }
                  },
                  "link": {
                    "value": {
                      "error": "not found: lab_companies",
                      "code": "not_found"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/webhooks": {
      "get": {
        "operationId": "listWebhooks",
        "summary": "The tenant's webhook subscriptions",
        "description": "Every subscription of the tenant (at most 20), by id; never a secret. Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session or an API token of their role. Not audited (a read). `no-store`.",
        "tags": [
          "webhooks"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "webhook_admin"
            ]
          }
        ],
        "responses": {
          "200": {
            "description": "The subscriptions.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookSubscriptionList"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "url": "https://erp.buyer.example/hooks/croppath",
                      "description": "Buyer ERP",
                      "event_types": [
                        "lot.sealed",
                        "shipment.departed"
                      ],
                      "status": "active",
                      "disabled_reason": null,
                      "disabled_at": null,
                      "consecutive_failures": 0,
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5,
                      "updated_at": 1790000000.5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createWebhook",
        "summary": "Register a webhook subscription (secret shown once)",
        "description": "Registers an HTTPS endpoint for the given event types; the server generates the signing secret, returns it in this response only and stores it encrypted under the deployment's key-encryption key. The URL must be https, without credentials or fragment, and every address its host resolves to must be public. Audited (`webhook.create`, in the same transaction, with the URL's host and the event types, never the secret). Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session or an API token of their role. Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "webhook_admin"
            ]
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookSubscriptionCreate"
              },
              "example": {
                "url": "https://erp.buyer.example/hooks/croppath",
                "event_types": [
                  "lot.sealed",
                  "shipment.departed"
                ],
                "description": "Buyer ERP"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The subscription, with its secret shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookSecret"
                },
                "example": {
                  "subscription": {
                    "id": 3,
                    "url": "https://erp.buyer.example/hooks/croppath",
                    "description": "Buyer ERP",
                    "event_types": [
                      "lot.sealed",
                      "shipment.departed"
                    ],
                    "status": "active",
                    "disabled_reason": null,
                    "disabled_at": null,
                    "consecutive_failures": 0,
                    "created_by": "admin@coop.example",
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5
                  },
                  "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw3qdbLeXcY4o="
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad URL (not https, credentials, a fragment, a host that does not resolve or resolves to an address that is not public), bad event types or description, or a bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the signing secret, which is stored only encrypted.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "url": {
                    "value": {
                      "error": "invalid url: https:// only",
                      "code": "invalid_url"
                    }
                  },
                  "private": {
                    "value": {
                      "error": "invalid url: the host resolves to an address that is not a public one",
                      "code": "invalid_url"
                    }
                  },
                  "resolve": {
                    "value": {
                      "error": "invalid url: the host does not resolve",
                      "code": "invalid_url"
                    }
                  },
                  "event_types": {
                    "value": {
                      "error": "invalid event_types: a non-empty list of distinct types from lot.sealed, lot.recalled, lot.withdrawn, lab_result.recorded, shipment.departed, lot.trust_tier_changed, report.filed",
                      "code": "invalid_event_types"
                    }
                  },
                  "description": {
                    "value": {
                      "error": "invalid description: at most 200 characters on one line",
                      "code": "invalid_description"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: secret",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The tenant holds 20 subscriptions already.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "subscription limit reached: at most 20 per tenant",
                  "code": "subscription_limit_reached"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK): a secret cannot be stored; nothing changed. Retry after `Retry-After` seconds once it is configured.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "webhooks unavailable: no key-encryption key is configured",
                  "code": "webhooks_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/webhooks/{id}": {
      "get": {
        "operationId": "getWebhook",
        "summary": "One webhook subscription",
        "description": "Never its secret. Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session or an API token of their role. Another tenant's answers like a missing one. `no-store`.",
        "tags": [
          "webhooks"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "webhook_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The subscription id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "responses": {
          "200": {
            "description": "The subscription.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookSubscription"
                },
                "example": {
                  "id": 3,
                  "url": "https://erp.buyer.example/hooks/croppath",
                  "description": "Buyer ERP",
                  "event_types": [
                    "lot.sealed",
                    "shipment.departed"
                  ],
                  "status": "active",
                  "disabled_reason": null,
                  "disabled_at": null,
                  "consecutive_failures": 0,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such subscription of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "patch": {
        "operationId": "updateWebhook",
        "summary": "Change, disable or enable a webhook subscription",
        "description": "Changes the URL (checked as on create), the event types, the description, or `enabled`. Disabling fails the pending deliveries (`subscription_disabled`, redeliverable once enabled again); enabling resets the failure count. Audited (`webhook.update`, with the host, event types and status before and after). Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session or an API token of their role.",
        "tags": [
          "webhooks"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "webhook_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The subscription id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookSubscriptionUpdate"
              },
              "example": {
                "enabled": false
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The subscription as changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookSubscription"
                },
                "example": {
                  "id": 3,
                  "url": "https://erp.buyer.example/hooks/croppath",
                  "description": "Buyer ERP",
                  "event_types": [
                    "lot.sealed",
                    "shipment.departed"
                  ],
                  "status": "disabled",
                  "disabled_reason": "manual",
                  "disabled_at": 1790003600.5,
                  "consecutive_failures": 0,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_at": 1790003600.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an empty body, an unknown field, a bad URL, event types, description or `enabled`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "url": {
                    "value": {
                      "error": "invalid url: https:// only",
                      "code": "invalid_url"
                    }
                  },
                  "private": {
                    "value": {
                      "error": "invalid url: the host resolves to an address that is not a public one",
                      "code": "invalid_url"
                    }
                  },
                  "resolve": {
                    "value": {
                      "error": "invalid url: the host does not resolve",
                      "code": "invalid_url"
                    }
                  },
                  "event_types": {
                    "value": {
                      "error": "invalid event_types: a non-empty list of distinct types from lot.sealed, lot.recalled, lot.withdrawn, lab_result.recorded, shipment.departed, lot.trust_tier_changed, report.filed",
                      "code": "invalid_event_types"
                    }
                  },
                  "description": {
                    "value": {
                      "error": "invalid description: at most 200 characters on one line",
                      "code": "invalid_description"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: secret",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "empty": {
                    "value": {
                      "error": "nothing to change: give url, event_types, description or enabled",
                      "code": "nothing_to_change"
                    }
                  },
                  "enabled": {
                    "value": {
                      "error": "invalid enabled: true or false",
                      "code": "invalid_enabled"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such subscription of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/webhooks/{id}/rotate-secret": {
      "post": {
        "operationId": "rotateWebhookSecret",
        "summary": "Replace a webhook subscription's secret (shown once)",
        "description": "A new secret replaces the old one at once: the next delivery is signed with it. Audited (`webhook.rotate_secret`, never the secret). Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session or an API token of their role. `no-store`. A session must have confirmed its password within the last 10 minutes (SELF-1-2, #183), else 401 `reauthentication_required` before anything is done.",
        "tags": [
          "webhooks"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "webhook_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The subscription id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "responses": {
          "200": {
            "description": "The subscription, with its new secret shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookSecret"
                },
                "example": {
                  "subscription": {
                    "id": 3,
                    "url": "https://erp.buyer.example/hooks/croppath",
                    "description": "Buyer ERP",
                    "event_types": [
                      "lot.sealed",
                      "shipment.departed"
                    ],
                    "status": "active",
                    "disabled_reason": null,
                    "disabled_at": null,
                    "consecutive_failures": 0,
                    "created_by": "admin@coop.example",
                    "created_at": 1790000000.5,
                    "updated_at": 1790000000.5
                  },
                  "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw3qdbLeXcY4o="
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id; or an Idempotency-Key header, which this operation refuses: its response holds the new signing secret, which is stored only encrypted.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "idempotency_key_not_supported": {
                    "value": {
                      "error": "idempotency key not supported",
                      "code": "idempotency_key_not_supported"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such subscription of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "No key-encryption key is configured (AGRITRACE_ISSUER_KEK): a secret cannot be stored; nothing changed. Retry after `Retry-After` seconds once it is configured.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "webhooks unavailable: no key-encryption key is configured",
                  "code": "webhooks_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/webhooks/{id}/deliveries": {
      "get": {
        "operationId": "listWebhookDeliveries",
        "summary": "A webhook subscription's delivery log",
        "description": "Newest first, one page (`limit`, default 50, at most 200; `cursor` from the previous page), optionally of one status. Deliveries finished more than 30 days ago are removed. Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session or an API token of their role. Not audited (a read). `no-store`.",
        "tags": [
          "webhooks"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "webhook_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The subscription id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only deliveries of this status.",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "delivered",
                "failed"
              ]
            },
            "example": "failed"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjQxfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of deliveries.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookDeliveryPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 41,
                      "subscription_id": 3,
                      "event_id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                      "event_type": "lot.sealed",
                      "status": "delivered",
                      "attempts": 1,
                      "next_attempt_at": null,
                      "last_attempt_at": 1790000003.2,
                      "last_status": 204,
                      "last_error": null,
                      "created_at": 1790000002.9,
                      "delivered_at": 1790000003.4
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `status`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "value": {
                      "error": "invalid status: one of pending, delivered, failed",
                      "code": "invalid_status"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such subscription of this tenant (another tenant's answers like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/webhooks/{id}/deliveries/{delivery}/redeliver": {
      "post": {
        "operationId": "redeliverWebhook",
        "summary": "Send a delivered or failed delivery again",
        "description": "The delivery is pending again, due now, with a fresh retry window (`attempts` from 0) and the same event id and body. Audited (`webhook.redeliver`). Allowed for tenant_admin and platform_admin acting for the tenant (X-Tenant), through a session or an API token of their role.",
        "tags": [
          "webhooks"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "webhook_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The subscription id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          },
          {
            "name": "delivery",
            "in": "path",
            "required": true,
            "description": "The delivery id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "41"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The delivery, pending again.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookDelivery"
                },
                "example": {
                  "id": 41,
                  "subscription_id": 3,
                  "event_id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                  "event_type": "lot.sealed",
                  "status": "pending",
                  "attempts": 0,
                  "next_attempt_at": 1790007200.5,
                  "last_attempt_at": 1790000003.2,
                  "last_status": 204,
                  "last_error": null,
                  "created_at": 1790000002.9,
                  "delivered_at": null
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such subscription of this tenant, or no such delivery of it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 41",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The subscription is disabled, or the delivery is still pending. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "disabled": {
                    "value": {
                      "error": "subscription disabled: enable it first",
                      "code": "subscription_disabled"
                    }
                  },
                  "pending": {
                    "value": {
                      "error": "delivery is pending: it is attempted again at its next attempt time",
                      "code": "delivery_is_pending"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/export-label": {
      "get": {
        "operationId": "getLotExportLabel",
        "summary": "A lot's export carton and pallet labels",
        "description": "The fields the destination market's export label prints, from the registry and the packing records (fruit name, origin, export country, orchard and packing house with their registration codes when cross-checked, packing date), a page of the selected cartons with their net mass, count and QR URL, the pallet totals and the lot's public URL, the template in force, and the problems that keep the label from being an export label (`ready` false). #273: the origin of a growing area coded by official administrative unit codes is its commune and province (Viet Nam has had no district level since 2025-07-01), given only with `admin_units=1`; an area not coded yet keeps its district and province. The company profile's address must be coded (or abroad) before the next label (`address_not_coded`). #288: with `label_code=1` each carton also has its lookup code (`label_code`), the 15-character code the label prints under the carton's QR code for a person whose QR code cannot be scanned; the scan page and `GET /v1/public/resolve` read it. A code that is not cross-checked against the published code lists is never given. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "market",
            "in": "query",
            "required": true,
            "description": "Destination market (ISO 3166-1 alpha-2); CN is the only one.",
            "schema": {
              "type": "string",
              "pattern": "^[A-Z]{2}$"
            },
            "example": "CN"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "First carton number of the selection (default: the lot's first).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 9999
            },
            "example": 1
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "Last carton number of the selection (default: the lot's last).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 9999
            },
            "example": 40
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page.",
            "schema": {
              "type": "string"
            },
            "example": "eyJjYXJ0b25fbm8iOjUwfQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 200.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            },
            "example": 50
          },
          {
            "name": "admin_units",
            "in": "query",
            "required": false,
            "description": "#273: `1` gives the origin as `{province, commune, district}` (the commune and province of a growing area coded by official administrative unit codes, `district` null; an area not coded yet keeps its district) and adds the producer's `commune`; `0` or none answers exactly as before, where a coded area's origin is null (the closed `{province, district}` has no commune); any other value is refused (400 `bad admin_units`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          },
          {
            "name": "label_code",
            "in": "query",
            "required": false,
            "description": "#288: `1` adds each carton's lookup code (`cartons[].label_code`); `0` or none leaves it out and answers exactly as before; any other value is refused (400 `bad label_code`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "responses": {
          "200": {
            "description": "The label of the selection, one page of cartons.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExportLabel"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "market": "CN",
                  "lot_status": "packed",
                  "template_version": 0,
                  "template": {
                    "mark": {
                      "zh": "输往中华人民共和国",
                      "en": "Exported to the People's Republic of China"
                    },
                    "export_country": {
                      "zh": "越南",
                      "en": "Vietnam"
                    },
                    "products": {
                      "durian": {
                        "zh": "榴莲",
                        "en": "Durian"
                      }
                    },
                    "fields": {
                      "fruit": {
                        "zh": "水果名称",
                        "en": "Fruit",
                        "required": true
                      },
                      "origin": {
                        "zh": "产地",
                        "en": "Origin",
                        "required": true
                      },
                      "export_country": {
                        "zh": "出口国家",
                        "en": "Country of export",
                        "required": true
                      },
                      "orchard": {
                        "zh": "果园名称或注册号",
                        "en": "Orchard name or registration number",
                        "required": true
                      },
                      "packing_house": {
                        "zh": "包装厂名称或注册号",
                        "en": "Packing house name or registration number",
                        "required": true
                      },
                      "producer": {
                        "zh": "生产商",
                        "en": "Producer",
                        "required": false
                      },
                      "packing_date": {
                        "zh": "包装日期",
                        "en": "Packing date",
                        "required": false
                      },
                      "net_mass": {
                        "zh": "净重",
                        "en": "Net weight",
                        "required": false
                      },
                      "count": {
                        "zh": "数量",
                        "en": "Count",
                        "required": false
                      },
                      "lot": {
                        "zh": "批号",
                        "en": "Lot",
                        "required": false
                      }
                    },
                    "require_cross_checked_codes": true,
                    "source": "Durian export label clause as published for the Malaysia and Laos protocols with China (same clause family as the Vietnam-China protocol of 2022-07-11; to be confirmed against the Vietnamese text): https://www.doa.gov.my/doa/resources/aktiviti_sumber/sumber_awam/maklumat_biosekuriti/pamplet_prosedur_pengeksportan_durian_segar_ke_china.pdf"
                  },
                  "fields": {
                    "fruit": {
                      "zh": "榴莲",
                      "en": "Durian"
                    },
                    "origin": {
                      "province": "Đắk Lắk",
                      "district": "Krông Pắc"
                    },
                    "export_country": {
                      "zh": "越南",
                      "en": "Vietnam"
                    },
                    "orchard": {
                      "name": "Vườn Bà Tư",
                      "code": null,
                      "check": "no_list",
                      "cross_checked": false
                    },
                    "packing_house": {
                      "name": "Nhà đóng gói Ea Kly",
                      "code": null,
                      "check": "no_list",
                      "cross_checked": false
                    },
                    "producer": {
                      "legal_name": "Hợp tác xã Sầu riêng Ea Kly",
                      "address": "Thôn 2, xã Ea Kly",
                      "district": "Krông Pắc",
                      "province": "Đắk Lắk",
                      "country": "VN"
                    },
                    "packing_date": "2026-09-30"
                  },
                  "pallet": {
                    "from": 1,
                    "to": 2,
                    "cartons": 2,
                    "fruit_count": 6,
                    "net_mass_kg": 17.4,
                    "qr_url": "https://txng.theio.vn/l/5b0e4c2a9d8f4e1a8c7b6a5d4e3f2a1b"
                  },
                  "cartons": [
                    {
                      "code": "C-014-0001",
                      "carton_no": 1,
                      "net_mass_kg": 8.5,
                      "fruit_count": 3,
                      "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60"
                    }
                  ],
                  "problems": [
                    "orchard_code_not_cross_checked",
                    "packing_house_code_not_cross_checked"
                  ],
                  "ready": false,
                  "next_cursor": "eyJjYXJ0b25fbm8iOjF9"
                }
              }
            }
          },
          "400": {
            "description": "No or an unknown market, a bad carton range, cursor or limit, `admin_units` or `label_code` not 0 or 1, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "market_required": {
                    "value": {
                      "error": "market is required",
                      "code": "market_is_required"
                    }
                  },
                  "invalid_market": {
                    "value": {
                      "error": "invalid market: one of CN",
                      "code": "invalid_market"
                    }
                  },
                  "invalid_from": {
                    "value": {
                      "error": "invalid from: a carton number from 1 to 9999",
                      "code": "invalid_from"
                    }
                  },
                  "invalid_to": {
                    "value": {
                      "error": "invalid to: not below from",
                      "code": "invalid_to"
                    }
                  },
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "bad_admin_units": {
                    "value": {
                      "error": "bad admin_units",
                      "code": "bad_admin_units"
                    }
                  },
                  "bad_label_code": {
                    "value": {
                      "error": "bad label_code",
                      "code": "bad_label_code"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "No or an unknown market, a bad carton range, cursor or limit, or a bad X-Request-Id.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "market_required": {
                      "value": {
                        "error": "market is required",
                        "code": "market_is_required"
                      }
                    },
                    "invalid_market": {
                      "value": {
                        "error": "invalid market: one of CN",
                        "code": "invalid_market"
                      }
                    },
                    "invalid_from": {
                      "value": {
                        "error": "invalid from: a carton number from 1 to 9999",
                        "code": "invalid_from"
                      }
                    },
                    "invalid_to": {
                      "value": {
                        "error": "invalid to: not below from",
                        "code": "invalid_to"
                      }
                    },
                    "bad_cursor": {
                      "value": {
                        "error": "bad cursor",
                        "code": "bad_cursor"
                      }
                    },
                    "bad_limit": {
                      "value": {
                        "error": "bad limit",
                        "code": "bad_limit"
                      }
                    },
                    "bad_request_id": {
                      "value": {
                        "error": "bad request id",
                        "code": "bad_request_id"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-sdk-description": "The fields the destination market's export label prints, from the registry and the packing records (fruit name, origin, export country, orchard and packing house with their registration codes when cross-checked, packing date), a page of the selected cartons with their net mass, count and QR URL, the pallet totals and the lot's public URL, the template in force, and the problems that keep the label from being an export label (`ready` false). A code that is not cross-checked against the published code lists is never given. Allowed for platform_admin, tenant_admin and auditor (the whole tenant) and for an operator signed in with a session (only the lots of its facilities). Not audited (a read)."
      }
    },
    "/v1/lots/{lot}/gs1": {
      "get": {
        "operationId": "getLotGs1Labels",
        "summary": "A lot's GS1 label data",
        "description": "#161: what the lot's GS1 labels print: the lot's GS1-128 element string (01)(10) and its lot-level Digital Link (resolved once the lot is sealed), a page of its cartons (`limit`, default 50, at most 200; `cursor`) with (01)(10)(21) and their Digital Links, and the pallets holding its cartons with (00). Same roles as reading the lot. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "packing"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code.",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJjYXJ0b25fbm8iOjUwfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's GS1 label data.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotGs1Labels"
                },
                "example": {
                  "lot": "LO-260928-014",
                  "gtin": "09520000000011",
                  "sealed": true,
                  "element_string": "(01)09520000000011(10)LO-260928-014",
                  "digital_link": "https://txng.theio.vn/01/09520000000011/10/LO-260928-014",
                  "cartons": [
                    {
                      "code": "C-014-0001",
                      "carton_no": 1,
                      "epc": "https://id.gs1.org/01/09520000000011/21/Xk3pQ9vT2mLr7Wb4Yz1A",
                      "element_string": "(01)09520000000011(10)LO-260928-014(21)Xk3pQ9vT2mLr7Wb4Yz1A",
                      "digital_link": "https://txng.theio.vn/01/09520000000011/10/LO-260928-014/21/Xk3pQ9vT2mLr7Wb4Yz1A"
                    }
                  ],
                  "pallets": [
                    {
                      "sscc": "095200000000000011",
                      "element_string": "(00)095200000000000011",
                      "lot_cartons": 40,
                      "first_carton": 1,
                      "last_carton": 40,
                      "cartons": 40
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lots/{lot}/export-label/prints": {
      "post": {
        "operationId": "recordExportLabelPrint",
        "summary": "Log a print of a lot's export labels",
        "description": "Records that the carton labels (`kind` carton) or the pallet label (`kind` pallet) of the cartons numbered `from` to `to` (default: the whole lot) were printed for `market`, with the template version printed. The body carries the `template_version` and the carton count (`cartons`, ExportLabel.pallet.cartons) of the label the console read and prints. Refused (409 `label_not_ready`, naming the problems) when the label is not ready for export, so the print log holds only export labels, and (409 `label_changed`) when the template version in force or the selection's carton count differs from what was sent, so the log never names a version or a range that was not printed. Raises no trust tier. Audited (`export_label.print`, in the same transaction). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities); auditor and lab are refused.",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ExportLabelPrintCreate"
              },
              "example": {
                "market": "CN",
                "kind": "carton",
                "from": 1,
                "to": 2,
                "template_version": 0,
                "cartons": 2
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The print log entry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExportLabelPrint"
                },
                "example": {
                  "id": 7,
                  "lot": "LO-260928-014",
                  "market": "CN",
                  "kind": "carton",
                  "from": 1,
                  "to": 2,
                  "cartons": 2,
                  "template_version": 0,
                  "printed_by": "packer@coop.example",
                  "printed_at": 1790000400.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a bad value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_market": {
                    "value": {
                      "error": "invalid market: one of CN",
                      "code": "invalid_market"
                    }
                  },
                  "invalid_kind": {
                    "value": {
                      "error": "invalid kind: carton or pallet",
                      "code": "invalid_kind"
                    }
                  },
                  "invalid_to": {
                    "value": {
                      "error": "invalid to: not below from",
                      "code": "invalid_to"
                    }
                  },
                  "invalid_template_version": {
                    "value": {
                      "error": "invalid template_version: an integer from 0 to 2147483647, as read from the label",
                      "code": "invalid_template_version"
                    }
                  },
                  "invalid_cartons": {
                    "value": {
                      "error": "invalid cartons: an integer from 0 to 9999, as read from the label",
                      "code": "invalid_cartons"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: copies",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The label is not ready for export (label_not_ready: the error names every problem, ExportLabel.problems), or it changed since the console read it (label_changed: the template version in force or the selection's carton count is not the one sent), so nothing is logged. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_ready": {
                    "value": {
                      "error": "label not ready: orchard_code_not_cross_checked, packing_house_code_not_cross_checked",
                      "code": "label_not_ready"
                    }
                  },
                  "label_changed": {
                    "value": {
                      "error": "label changed: template version 1 is in force, not 0",
                      "code": "label_changed"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/export-label-templates": {
      "get": {
        "operationId": "listExportLabelTemplates",
        "summary": "The export label templates",
        "description": "The label template in force of every destination market (version 0: the built-in default). Allowed for platform_admin only. Not audited (a read).",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "responses": {
          "200": {
            "description": "Every market's template.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExportLabelTemplateList"
                },
                "example": {
                  "items": [
                    {
                      "market": "CN",
                      "version": 0,
                      "template": {
                        "mark": {
                          "zh": "输往中华人民共和国",
                          "en": "Exported to the People's Republic of China"
                        },
                        "export_country": {
                          "zh": "越南",
                          "en": "Vietnam"
                        },
                        "products": {
                          "durian": {
                            "zh": "榴莲",
                            "en": "Durian"
                          }
                        },
                        "fields": {
                          "fruit": {
                            "zh": "水果名称",
                            "en": "Fruit",
                            "required": true
                          },
                          "origin": {
                            "zh": "产地",
                            "en": "Origin",
                            "required": true
                          },
                          "export_country": {
                            "zh": "出口国家",
                            "en": "Country of export",
                            "required": true
                          },
                          "orchard": {
                            "zh": "果园名称或注册号",
                            "en": "Orchard name or registration number",
                            "required": true
                          },
                          "packing_house": {
                            "zh": "包装厂名称或注册号",
                            "en": "Packing house name or registration number",
                            "required": true
                          },
                          "producer": {
                            "zh": "生产商",
                            "en": "Producer",
                            "required": false
                          },
                          "packing_date": {
                            "zh": "包装日期",
                            "en": "Packing date",
                            "required": false
                          },
                          "net_mass": {
                            "zh": "净重",
                            "en": "Net weight",
                            "required": false
                          },
                          "count": {
                            "zh": "数量",
                            "en": "Count",
                            "required": false
                          },
                          "lot": {
                            "zh": "批号",
                            "en": "Lot",
                            "required": false
                          }
                        },
                        "require_cross_checked_codes": true,
                        "source": "Durian export label clause as published for the Malaysia and Laos protocols with China (same clause family as the Vietnam-China protocol of 2022-07-11; to be confirmed against the Vietnamese text): https://www.doa.gov.my/doa/resources/aktiviti_sumber/sumber_awam/maklumat_biosekuriti/pamplet_prosedur_pengeksportan_durian_segar_ke_china.pdf"
                      },
                      "updated_at": null,
                      "updated_by": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (a principal without a role), tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/export-label-templates/{market}": {
      "put": {
        "operationId": "putExportLabelTemplate",
        "summary": "Edit a market's export label template",
        "description": "Appends the market's next template version, which every later label prints (text only: captions, the mark, fruit names, which fields are required and whether codes must be cross-checked). Earlier versions are kept; a print log entry names the version it printed. Audited (`export_label_template.put`, in the same transaction). Allowed for platform_admin only.",
        "tags": [
          "packing"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "market",
            "in": "path",
            "required": true,
            "description": "Destination market (ISO 3166-1 alpha-2).",
            "schema": {
              "type": "string"
            },
            "example": "CN"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ExportLabelTemplate"
              },
              "example": {
                "mark": {
                  "zh": "输往中华人民共和国",
                  "en": "Exported to the People's Republic of China"
                },
                "export_country": {
                  "zh": "越南",
                  "en": "Vietnam"
                },
                "products": {
                  "durian": {
                    "zh": "榴莲",
                    "en": "Durian"
                  }
                },
                "fields": {
                  "fruit": {
                    "zh": "水果名称",
                    "en": "Fruit",
                    "required": true
                  },
                  "origin": {
                    "zh": "产地",
                    "en": "Origin",
                    "required": true
                  },
                  "export_country": {
                    "zh": "出口国家",
                    "en": "Country of export",
                    "required": true
                  },
                  "orchard": {
                    "zh": "果园名称或注册号",
                    "en": "Orchard name or registration number",
                    "required": true
                  },
                  "packing_house": {
                    "zh": "包装厂名称或注册号",
                    "en": "Packing house name or registration number",
                    "required": true
                  },
                  "producer": {
                    "zh": "生产商",
                    "en": "Producer",
                    "required": false
                  },
                  "packing_date": {
                    "zh": "包装日期",
                    "en": "Packing date",
                    "required": false
                  },
                  "net_mass": {
                    "zh": "净重",
                    "en": "Net weight",
                    "required": false
                  },
                  "count": {
                    "zh": "数量",
                    "en": "Count",
                    "required": false
                  },
                  "lot": {
                    "zh": "批号",
                    "en": "Lot",
                    "required": false
                  }
                },
                "require_cross_checked_codes": true,
                "source": "Durian export label clause as published for the Malaysia and Laos protocols with China (same clause family as the Vietnam-China protocol of 2022-07-11; to be confirmed against the Vietnamese text): https://www.doa.gov.my/doa/resources/aktiviti_sumber/sumber_awam/maklumat_biosekuriti/pamplet_prosedur_pengeksportan_durian_segar_ke_china.pdf"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The new version.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExportLabelTemplateView"
                },
                "example": {
                  "market": "CN",
                  "version": 1,
                  "template": {
                    "mark": {
                      "zh": "输往中华人民共和国",
                      "en": "Exported to the People's Republic of China"
                    },
                    "export_country": {
                      "zh": "越南",
                      "en": "Vietnam"
                    },
                    "products": {
                      "durian": {
                        "zh": "榴莲",
                        "en": "Durian"
                      }
                    },
                    "fields": {
                      "fruit": {
                        "zh": "水果名称",
                        "en": "Fruit",
                        "required": true
                      },
                      "origin": {
                        "zh": "产地",
                        "en": "Origin",
                        "required": true
                      },
                      "export_country": {
                        "zh": "出口国家",
                        "en": "Country of export",
                        "required": true
                      },
                      "orchard": {
                        "zh": "果园名称或注册号",
                        "en": "Orchard name or registration number",
                        "required": true
                      },
                      "packing_house": {
                        "zh": "包装厂名称或注册号",
                        "en": "Packing house name or registration number",
                        "required": true
                      },
                      "producer": {
                        "zh": "生产商",
                        "en": "Producer",
                        "required": false
                      },
                      "packing_date": {
                        "zh": "包装日期",
                        "en": "Packing date",
                        "required": false
                      },
                      "net_mass": {
                        "zh": "净重",
                        "en": "Net weight",
                        "required": false
                      },
                      "count": {
                        "zh": "数量",
                        "en": "Count",
                        "required": false
                      },
                      "lot": {
                        "zh": "批号",
                        "en": "Lot",
                        "required": false
                      }
                    },
                    "require_cross_checked_codes": true,
                    "source": "Durian export label clause as published for the Malaysia and Laos protocols with China (same clause family as the Vietnam-China protocol of 2022-07-11; to be confirmed against the Vietnamese text): https://www.doa.gov.my/doa/resources/aktiviti_sumber/sumber_awam/maklumat_biosekuriti/pamplet_prosedur_pengeksportan_durian_segar_ke_china.pdf"
                  },
                  "updated_at": 1790000500.0,
                  "updated_by": "platform@croppath.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown market, an unknown field or a bad text, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_market": {
                    "value": {
                      "error": "invalid market: one of CN",
                      "code": "invalid_market"
                    }
                  },
                  "invalid_template": {
                    "value": {
                      "error": "invalid template: mark needs zh and en",
                      "code": "invalid_template"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: script",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments/{code}/consignee": {
      "put": {
        "operationId": "setShipmentConsignee",
        "summary": "Set the shipment's consignee",
        "description": "Replaces the consignee of the shipment (#153): legal name, address, ISO 3166-1 alpha-2 country, optional GLN (GS1 check digit) and tax or importer registration id. Edited freely while the shipment is open; after the departure a `reason` is required and the change is kept as an amendment. Audited (`shipment.consignee.set`): the row names the changed fields, the consignee's country, the document types and the amendment id, never a name or an address. Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities); auditor and lab are refused.",
        "tags": [
          "shipping"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "SH-260930-01"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ShipmentConsigneeSet"
              },
              "example": {
                "consignee": {
                  "name": "Guangxi Fresh Import Co., Ltd.",
                  "address": "88 Youyi Road, Pingxiang, Guangxi",
                  "country": "CN",
                  "gln": "6901234000009",
                  "registration_id": "CIQ-4500/2026"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The shipment with its consignee, documents, paperwork and amendments.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Shipment"
                },
                "example": {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "setpoint_c": 13.0,
                  "tolerance_c": 2.0,
                  "logger_interval_minutes": 15,
                  "logger": {
                    "device_id": "reefer-logger-0731"
                  },
                  "status": "departed",
                  "created_by": "shipper@coop.example",
                  "created_at": 1790040000.0,
                  "departed_by": "shipper@coop.example",
                  "departed_at": 1790042400.0,
                  "lots": [
                    {
                      "lot": "LO-260928-014",
                      "status": "shipped",
                      "cartons": 41,
                      "seal_no": "0492117",
                      "sealed_at": 1790040600.0,
                      "current_seal_no": "0492117",
                      "seal_matches": true,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041000.0
                    }
                  ],
                  "logger_check": {
                    "status": "matched",
                    "readings": 9,
                    "considered": 9,
                    "first_at": 1790040600.0,
                    "last_at": 1790047800.0,
                    "min_c": 12.6,
                    "max_c": 13.4,
                    "seal_at": 1790040600.0,
                    "until": 1790042400.0,
                    "gap_count": 0,
                    "gaps": [],
                    "out_of_range_count": 0,
                    "out_of_range": [],
                    "complete": true,
                    "within_setpoint": true
                  },
                  "national_portal": {
                    "rows": 386,
                    "delivered": 386,
                    "pending": 0,
                    "failing": 0,
                    "filed": true
                  },
                  "consignee": {
                    "name": "Guangxi Fresh Import Co., Ltd.",
                    "address": "88 Youyi Road, Pingxiang, Guangxi",
                    "country": "CN",
                    "gln": "6901234000009",
                    "registration_id": "CIQ-4500/2026"
                  },
                  "documents": [
                    {
                      "type": "phytosanitary_certificate",
                      "number": "VN-PC/2026/0123",
                      "issued_on": "2026-09-29",
                      "attachment_sha256": null,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041200.0
                    },
                    {
                      "type": "test_report",
                      "number": "VILAS-1234/26",
                      "issued_on": "2026-09-28",
                      "attachment_sha256": null,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041200.0
                    }
                  ],
                  "paperwork": {
                    "required": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "missing": [],
                    "complete": true
                  },
                  "amendments": []
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a bad member, or a change to a departed shipment without a reason.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason_is_required": {
                    "value": {
                      "error": "reason is required: the shipment departed, a change is an amendment",
                      "code": "reason_is_required"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: consignee and optionally reason",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_consignee_country": {
                    "value": {
                      "error": "invalid consignee country: an ISO 3166-1 alpha-2 code in capitals, e.g. CN",
                      "code": "invalid_consignee_country"
                    }
                  },
                  "invalid_consignee_gln": {
                    "value": {
                      "error": "invalid consignee gln: 13 digits with a valid GS1 check digit",
                      "code": "invalid_consignee_gln"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment for this tenant: a shipment of another tenant, or departing a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: SH-260930-01",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The departed shipment already keeps the most amendments.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "too_many_amendments": {
                    "value": {
                      "error": "too many amendments: a shipment keeps at most 50",
                      "code": "too_many_amendments"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments/{code}/documents": {
      "put": {
        "operationId": "setShipmentDocuments",
        "summary": "Set the shipment's document references",
        "description": "Replaces the shipment's document references (#153): each a type from a fixed list (phytosanitary certificate, certificate of origin, commercial invoice, packing list, customs declaration, bill of lading, air waybill, test report, other), a number, the issue date and optionally the SHA-256 of a PDF the tenant uploaded, which stays staff-only. An unchanged reference keeps who added it and when. Edited freely while the shipment is open; after the departure a `reason` is required and the change is kept as an amendment. Audited (`shipment.documents.set`): the row names the changed fields, the consignee's country, the document types and the amendment id, never a name or an address. Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only shipments departing its facilities); auditor and lab are refused.",
        "tags": [
          "shipping"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "SH-260930-01"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ShipmentDocumentsSet"
              },
              "example": {
                "documents": [
                  {
                    "type": "phytosanitary_certificate",
                    "number": "VN-PC/2026/0123",
                    "issued_on": "2026-09-29"
                  },
                  {
                    "type": "test_report",
                    "number": "VILAS-1234/26",
                    "issued_on": "2026-09-28"
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The shipment with its consignee, documents, paperwork and amendments.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Shipment"
                },
                "example": {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "setpoint_c": 13.0,
                  "tolerance_c": 2.0,
                  "logger_interval_minutes": 15,
                  "logger": {
                    "device_id": "reefer-logger-0731"
                  },
                  "status": "departed",
                  "created_by": "shipper@coop.example",
                  "created_at": 1790040000.0,
                  "departed_by": "shipper@coop.example",
                  "departed_at": 1790042400.0,
                  "lots": [
                    {
                      "lot": "LO-260928-014",
                      "status": "shipped",
                      "cartons": 41,
                      "seal_no": "0492117",
                      "sealed_at": 1790040600.0,
                      "current_seal_no": "0492117",
                      "seal_matches": true,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041000.0
                    }
                  ],
                  "logger_check": {
                    "status": "matched",
                    "readings": 9,
                    "considered": 9,
                    "first_at": 1790040600.0,
                    "last_at": 1790047800.0,
                    "min_c": 12.6,
                    "max_c": 13.4,
                    "seal_at": 1790040600.0,
                    "until": 1790042400.0,
                    "gap_count": 0,
                    "gaps": [],
                    "out_of_range_count": 0,
                    "out_of_range": [],
                    "complete": true,
                    "within_setpoint": true
                  },
                  "national_portal": {
                    "rows": 386,
                    "delivered": 386,
                    "pending": 0,
                    "failing": 0,
                    "filed": true
                  },
                  "consignee": {
                    "name": "Guangxi Fresh Import Co., Ltd.",
                    "address": "88 Youyi Road, Pingxiang, Guangxi",
                    "country": "CN",
                    "gln": "6901234000009",
                    "registration_id": "CIQ-4500/2026"
                  },
                  "documents": [
                    {
                      "type": "phytosanitary_certificate",
                      "number": "VN-PC/2026/0123",
                      "issued_on": "2026-09-29",
                      "attachment_sha256": null,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041200.0
                    },
                    {
                      "type": "test_report",
                      "number": "VILAS-1234/26",
                      "issued_on": "2026-09-28",
                      "attachment_sha256": null,
                      "added_by": "shipper@coop.example",
                      "added_at": 1790041200.0
                    }
                  ],
                  "paperwork": {
                    "required": [
                      "consignee",
                      "phytosanitary_certificate",
                      "test_report"
                    ],
                    "missing": [],
                    "complete": true
                  },
                  "amendments": []
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a bad member, or a change to a departed shipment without a reason.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason_is_required": {
                    "value": {
                      "error": "reason is required: the shipment departed, a change is an amendment",
                      "code": "reason_is_required"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: documents and optionally reason",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_document_type": {
                    "value": {
                      "error": "invalid document type: one of phytosanitary_certificate, certificate_of_origin, commercial_invoice, packing_list, customs_declaration, bill_of_lading, air_waybill, test_report, other",
                      "code": "invalid_document_type"
                    }
                  },
                  "invalid_document_issued_on": {
                    "value": {
                      "error": "invalid document issued_on: a date YYYY-MM-DD from 2000-01-01, not in the future",
                      "code": "invalid_document_issued_on"
                    }
                  },
                  "invalid_documents": {
                    "value": {
                      "error": "invalid documents: phytosanitary_certificate VN-PC/2026/0123 is listed twice",
                      "code": "invalid_documents"
                    }
                  },
                  "unknown_attachment": {
                    "value": {
                      "error": "unknown attachment: a PDF this tenant uploaded",
                      "code": "unknown_attachment"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role_not_permitted": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant_not_allowed": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf_token_missing_or_invalid": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment for this tenant: a shipment of another tenant, or departing a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: SH-260930-01",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The departed shipment already keeps the most amendments.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "too_many_amendments": {
                    "value": {
                      "error": "too many amendments: a shipment keeps at most 50",
                      "code": "too_many_amendments"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/shipments/{code}/sscc": {
      "get": {
        "operationId": "getShipmentSscc",
        "summary": "A shipment's container load SSCC",
        "description": "#161: the SSCC of the shipment's container load, null until set. Same roles as reading the shipment. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "shipping"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code.",
            "schema": {
              "type": "string"
            },
            "example": "SH-2026-0042"
          }
        ],
        "responses": {
          "200": {
            "description": "The load's SSCC.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ShipmentSscc"
                },
                "example": {
                  "shipment": "SH-2026-0042",
                  "sscc": "095200000000000011",
                  "epc": "https://id.gs1.org/00/095200000000000011",
                  "element_string": "(00)095200000000000011"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: SH-2026-0042",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "setShipmentSscc",
        "summary": "Set or allocate a container load's SSCC",
        "description": "#161: while the shipment is open. Its departure event then names the SSCC as its EPC, after the load's aggregation event (the pallets and the loose cartons of the lot into the load). Unique within the company. Same roles as the other shipment writes. Audited (`shipment.sscc.set`) in the company's activity log. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "shipping"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "Shipment code.",
            "schema": {
              "type": "string"
            },
            "example": "SH-2026-0042"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SsccChange"
              },
              "example": {
                "sscc": "106141411234567897"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The load's SSCC.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ShipmentSscc"
                },
                "example": {
                  "shipment": "SH-2026-0042",
                  "sscc": "106141411234567897",
                  "epc": "https://id.gs1.org/00/106141411234567897",
                  "element_string": "(00)106141411234567897"
                }
              }
            }
          },
          "400": {
            "description": "A body other than {\"sscc\": <18 digits>} or {\"allocate\": true}, an SSCC whose check digit is wrong or that carries the platform's prefix, invalid JSON or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: {\"sscc\": \"<18 digits>\"} or {\"allocate\": true}",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_sscc": {
                    "value": {
                      "error": "invalid sscc: 18 digits with a valid GS1 check digit",
                      "code": "invalid_sscc"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token, OAuth2 access token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such shipment for this company: one of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: SH-2026-0042",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The shipment departed, the SSCC is in use by the company, or no GS1 company prefix is configured.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "departed": {
                    "value": {
                      "error": "shipment departed: its container load keeps its sscc",
                      "code": "shipment_departed"
                    }
                  },
                  "sscc": {
                    "value": {
                      "error": "sscc already in use by the company",
                      "code": "sscc_already_in_use_by_the_company"
                    }
                  },
                  "prefix": {
                    "value": {
                      "error": "prefix not configured: the platform has no GS1 company prefix yet; enter a number of the company's own GS1 membership",
                      "code": "prefix_not_configured"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/harvest-keys": {
      "get": {
        "operationId": "listHarvestKeys",
        "summary": "Harvest app registrations of the caller's tenant",
        "description": "#160: registrations ordered by kid, with keyset pagination (at most 100 per page). An operator sees only those of its facilities. Allowed for platform_admin, tenant_admin, auditor and operator (its facilities).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of registrations.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6Imtuay0xIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of registrations.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestKeyPage"
                },
                "example": {
                  "items": [
                    {
                      "kid": "harvest-19fcfa6012e7f761a1f1e408:k1",
                      "device_id": "harvest-19fcfa6012e7f761a1f1e408",
                      "tenant": "coop-dl",
                      "facility": "VN-DL-PH-01",
                      "label": "Weighing desk phone",
                      "status": "pending",
                      "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                      "fingerprint": "19fc…e0d9",
                      "requested_by": "op@coop.example",
                      "requested_at": 1790000000.5,
                      "decided_by": null,
                      "decided_at": null,
                      "revoked_at": null,
                      "revoke_reason": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "registerHarvestKey",
        "summary": "Ask to register a harvest app install's key",
        "description": "#160: the harvest app (/harvest) generated a non-extractable ECDSA P-256 key and sends its public half. The registration is `pending` until a tenant admin approves or rejects it. Sending the same key again for the same facility answers the stored registration with 200, whatever its status. Audited (`harvest_key.register`, with the kid, device, facility and fingerprint; never the PEM). Allowed for platform_admin, tenant_admin and operator (its facilities).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/HarvestKeyRegister"
              },
              "example": {
                "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n",
                "facility": "VN-DL-PH-01",
                "label": "Weighing desk phone"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The same key was registered before for this facility: its registration, unchanged.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestKey"
                },
                "example": {
                  "kid": "harvest-19fcfa6012e7f761a1f1e408:k1",
                  "device_id": "harvest-19fcfa6012e7f761a1f1e408",
                  "tenant": "coop-dl",
                  "facility": "VN-DL-PH-01",
                  "label": "Weighing desk phone",
                  "status": "approved",
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "requested_by": "op@coop.example",
                  "requested_at": 1790000000.5,
                  "decided_by": "admin@coop.example",
                  "decided_at": 1790003600.0,
                  "revoked_at": null,
                  "revoke_reason": null
                }
              }
            }
          },
          "201": {
            "description": "The new pending registration.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestKey"
                },
                "example": {
                  "kid": "harvest-19fcfa6012e7f761a1f1e408:k1",
                  "device_id": "harvest-19fcfa6012e7f761a1f1e408",
                  "tenant": "coop-dl",
                  "facility": "VN-DL-PH-01",
                  "label": "Weighing desk phone",
                  "status": "pending",
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "requested_by": "op@coop.example",
                  "requested_at": 1790000000.5,
                  "decided_by": null,
                  "decided_at": null,
                  "revoked_at": null,
                  "revoke_reason": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, an unacceptable PEM, a facility that is not one of the caller's tenant within its scope, an invalid label, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_public_key_pem": {
                    "value": {
                      "error": "invalid public_key_pem: an EC P-256 public key as PEM SubjectPublicKeyInfo",
                      "code": "invalid_public_key_pem"
                    }
                  },
                  "unknown_facility": {
                    "value": {
                      "error": "unknown facility",
                      "code": "unknown_facility"
                    }
                  },
                  "invalid_label": {
                    "value": {
                      "error": "invalid label: 1 to 100 characters without control characters",
                      "code": "invalid_label"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The key is registered by another tenant or for another facility (whose is never said), or the derived device or key id is taken. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed. SELF-2-8 (#197): or the facility is a company's proposal CropPath has not approved yet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_already_registered": {
                    "value": {
                      "error": "key already registered",
                      "code": "key_already_registered"
                    }
                  },
                  "key_id_taken": {
                    "value": {
                      "error": "key id taken",
                      "code": "key_id_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  },
                  "facility_not_approved": {
                    "value": {
                      "error": "facility not approved",
                      "code": "facility_not_approved"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/harvest-keys/{kid}": {
      "get": {
        "operationId": "getHarvestKey",
        "summary": "One harvest app registration",
        "description": "#160: the registration's state; the app polls it while it waits for approval. Allowed for platform_admin, tenant_admin, auditor and operator (its facilities).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "kid",
            "in": "path",
            "required": true,
            "description": "Key id of the registration.",
            "schema": {
              "type": "string"
            },
            "example": "harvest-19fcfa6012e7f761a1f1e408:k1"
          }
        ],
        "responses": {
          "200": {
            "description": "The registration.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestKey"
                },
                "example": {
                  "kid": "harvest-19fcfa6012e7f761a1f1e408:k1",
                  "device_id": "harvest-19fcfa6012e7f761a1f1e408",
                  "tenant": "coop-dl",
                  "facility": "VN-DL-PH-01",
                  "label": "Weighing desk phone",
                  "status": "approved",
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "requested_by": "op@coop.example",
                  "requested_at": 1790000000.5,
                  "decided_by": "admin@coop.example",
                  "decided_at": 1790003600.0,
                  "revoked_at": null,
                  "revoke_reason": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such registration for this tenant and scope: another tenant's, or one of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: harvest-19fcfa6012e7f761a1f1e408:k1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/harvest-keys/{kid}/approve": {
      "post": {
        "operationId": "approveHarvestKey",
        "summary": "Approve a pending harvest app registration",
        "description": "#160: a tenant admin approved the registration (final). The install's device (profile `vn.agritrace.harvest-app`, active, at the registration's facility) and its active device key are created in the same transaction; ingest accepts its signed harvest envelopes from then on. The deciding actor is the principal. Audited (`harvest_key.approve`). Allowed for platform_admin and tenant_admin. Second admin approval (INTEGRITY-3, #203): while the company requires a second admin (PUT /v1/company/four-eyes), a direct call answers 403 `second_admin_approval_required` before anything is done (no audit row, no Idempotency-Key used): ask for it with POST /v1/approval-requests, and another admin of the company approves it.",
        "x-sdk-description": "#160: a tenant admin approved the registration (final). The install's device (profile `vn.agritrace.harvest-app`, active, at the registration's facility) and its active device key are created in the same transaction; ingest accepts its signed harvest envelopes from then on. The deciding actor is the principal. Audited (`harvest_key.approve`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "kid",
            "in": "path",
            "required": true,
            "description": "Key id of the registration.",
            "schema": {
              "type": "string"
            },
            "example": "harvest-19fcfa6012e7f761a1f1e408:k1"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The registration, approved.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestKey"
                },
                "example": {
                  "kid": "harvest-19fcfa6012e7f761a1f1e408:k1",
                  "device_id": "harvest-19fcfa6012e7f761a1f1e408",
                  "tenant": "coop-dl",
                  "facility": "VN-DL-PH-01",
                  "label": "Weighing desk phone",
                  "status": "approved",
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "requested_by": "op@coop.example",
                  "requested_at": 1790000000.5,
                  "decided_by": "admin@coop.example",
                  "decided_at": 1790003600.0,
                  "revoked_at": null,
                  "revoke_reason": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such registration for this tenant and scope: another tenant's, or one of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: harvest-19fcfa6012e7f761a1f1e408:k1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The registration is no longer pending, or (approval) its device or key id was taken since. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "registration_already_decided": {
                    "value": {
                      "error": "registration already decided",
                      "code": "registration_already_decided"
                    }
                  },
                  "key_id_taken": {
                    "value": {
                      "error": "key id taken",
                      "code": "key_id_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/harvest-keys/{kid}/reject": {
      "post": {
        "operationId": "rejectHarvestKey",
        "summary": "Reject a pending harvest app registration",
        "description": "#160: a tenant admin rejected the registration (final). No device or key is created; the install makes a new key. The deciding actor is the principal. Audited (`harvest_key.reject`). Allowed for platform_admin and tenant_admin.",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "kid",
            "in": "path",
            "required": true,
            "description": "Key id of the registration.",
            "schema": {
              "type": "string"
            },
            "example": "harvest-19fcfa6012e7f761a1f1e408:k1"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The registration, rejected.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HarvestKey"
                },
                "example": {
                  "kid": "harvest-19fcfa6012e7f761a1f1e408:k1",
                  "device_id": "harvest-19fcfa6012e7f761a1f1e408",
                  "tenant": "coop-dl",
                  "facility": "VN-DL-PH-01",
                  "label": "Weighing desk phone",
                  "status": "rejected",
                  "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
                  "fingerprint": "19fc…e0d9",
                  "requested_by": "op@coop.example",
                  "requested_at": 1790000000.5,
                  "decided_by": "admin@coop.example",
                  "decided_at": 1790003600.0,
                  "revoked_at": null,
                  "revoke_reason": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such registration for this tenant and scope: another tenant's, or one of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: harvest-19fcfa6012e7f761a1f1e408:k1",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The registration is no longer pending, or (approval) its device or key id was taken since. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "registration_already_decided": {
                    "value": {
                      "error": "registration already decided",
                      "code": "registration_already_decided"
                    }
                  },
                  "key_id_taken": {
                    "value": {
                      "error": "key id taken",
                      "code": "key_id_taken"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/device-approvals": {
      "get": {
        "operationId": "listDeviceApprovals",
        "summary": "The platform's device approval queue",
        "description": "#201: every company's devices and gateways with the given approval (default `pending`; the pending queue also lists an approved one with an active key no platform admin approved yet), ordered by id (devices and gateways share one id namespace), with keyset pagination (at most 100 per page), each with its company, facility, profile, active key fingerprints and approvals, who registered it and when. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "approval",
            "in": "query",
            "required": false,
            "description": "The approval to list.",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "approved",
                "rejected"
              ],
              "default": "pending"
            },
            "example": "pending"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "`next_cursor` of the previous page of the queue.",
            "schema": {
              "type": "string"
            },
            "example": "eyJhZnRlciI6Imtuay0xIn0"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the queue.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeviceApprovalPage"
                },
                "example": {
                  "items": [
                    {
                      "kind": "device",
                      "id": "knk-7",
                      "tenant": "coop-dl",
                      "tenant_name": "Coop DL",
                      "site": "ph1",
                      "facility": "VN-TGPH-021",
                      "profile": "vn.agritrace.durian-knocker",
                      "display_name": "Line A2 knocker",
                      "registered_by": "admin@coop.example",
                      "registered_at": 1790000000.5,
                      "approval": "pending",
                      "approval_reason": null,
                      "approval_at": null,
                      "approval_by": null,
                      "keys": [
                        {
                          "kid": "knk-7-k1",
                          "fingerprint": "3f9a…c21e",
                          "fingerprint_sha256": "3f9a00000000000000000000000000000000000000000000000000000000c21e",
                          "approval": "pending"
                        }
                      ]
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "An unknown approval, a cursor that is not one this API issued, a limit out of range, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_approval": {
                    "value": {
                      "error": "invalid approval: pending, approved or rejected",
                      "code": "invalid_approval"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices/{id}/approve": {
      "post": {
        "operationId": "approveDevice",
        "summary": "Approve a device (platform)",
        "description": "#201: a platform admin approves a device of any company, so evidence from it counts as Device-recorded or above. Idempotent: an approved one keeps its first approval. The body lists the waiting keys the platform admin saw in the queue: exactly those are approved with it (the audit row names them, `approved_keys`); a key the company registered since stays pending, so its evidence stays Self-declared and the device is listed in the queue again. 409, and nothing changes, when a listed key is no longer waiting (revoked, approved meanwhile, or not this device's). Audited (`device.approve`) in the device's company's activity log. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The device id.",
            "schema": {
              "type": "string"
            },
            "example": "knk-7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DeviceApproval"
              },
              "example": {
                "keys": [
                  "knk-7-k2"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The device with its approval.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeviceApprovalItem"
                },
                "example": {
                  "kind": "device",
                  "id": "knk-7",
                  "tenant": "coop-dl",
                  "tenant_name": "Coop DL",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "profile": "vn.agritrace.durian-knocker",
                  "display_name": "Line A2 knocker",
                  "registered_by": "admin@coop.example",
                  "registered_at": 1790000000.5,
                  "approval": "approved",
                  "approval_reason": null,
                  "approval_at": 1790000200.0,
                  "approval_by": "support@croppath.example",
                  "keys": [
                    {
                      "kid": "knk-7-k1",
                      "fingerprint": "3f9a…c21e",
                      "fingerprint_sha256": "3f9a00000000000000000000000000000000000000000000000000000000c21e",
                      "approval": "approved"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "An unknown field, a missing or malformed keys list, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_keys": {
                    "value": {
                      "error": "invalid keys: a list of up to 100 distinct key ids",
                      "code": "invalid_keys"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the device's company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device in any company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "A listed key is no longer waiting for approval (revoked, approved meanwhile, or not this device's): reload the queue. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_not_waiting_for_approval": {
                    "value": {
                      "error": "key not waiting for approval",
                      "code": "key_not_waiting_for_approval"
                    }
                  },
                  "placement_required": {
                    "summary": "SENS-A2 (#225): the device has no placement in force; record one (POST /v1/devices/{id}/placements) first",
                    "value": {
                      "error": "placement required: record where the device is installed before approving it",
                      "code": "placement_required"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices/{id}/reject": {
      "post": {
        "operationId": "rejectDevice",
        "summary": "Reject a device (platform)",
        "description": "#201: a platform admin rejects a device of any company, pending or approved (withdrawing its approval), with a reason shown to the company. Evidence from it then counts as Self-declared: open lots are lowered at their recompute, a sealed lot's tier can only be lowered. 409 when it is already rejected. Audited (`device.reject`) in the device's company's activity log. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The device id.",
            "schema": {
              "type": "string"
            },
            "example": "knk-7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DeviceRejection"
              },
              "example": {
                "reason": "Serial number does not match the scale's calibration certificate."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The device with its approval.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeviceApprovalItem"
                },
                "example": {
                  "kind": "device",
                  "id": "knk-7",
                  "tenant": "coop-dl",
                  "tenant_name": "Coop DL",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "profile": "vn.agritrace.durian-knocker",
                  "display_name": "Line A2 knocker",
                  "registered_by": "admin@coop.example",
                  "registered_at": 1790000000.5,
                  "approval": "rejected",
                  "approval_reason": "Serial number does not match.",
                  "approval_at": 1790000200.0,
                  "approval_by": "support@croppath.example",
                  "keys": [
                    {
                      "kid": "knk-7-k1",
                      "fingerprint": "3f9a…c21e",
                      "fingerprint_sha256": "3f9a00000000000000000000000000000000000000000000000000000000c21e",
                      "approval": "approved"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "An unknown field (`keys` belongs to an approval), a missing or too long reason, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: a string of 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the device's company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device in any company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The device is already rejected. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "device_already_rejected": {
                    "value": {
                      "error": "device already rejected",
                      "code": "device_already_rejected"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices/{id}/placements": {
      "get": {
        "operationId": "listDevicePlacements",
        "summary": "A device's placement versions",
        "description": "SENS-A2 (#225): every placement version CropPath recorded for a device of the company, newest first, with the growing area it is bound to, the surveyed install point and the commissioning record. Same roles as reading the device; an operator reads only devices of its facilities. `recorded_by` (who at CropPath recorded it) is returned to platform admins only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "soil-07"
          }
        ],
        "responses": {
          "200": {
            "description": "The device's placement versions.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DevicePlacements"
                },
                "example": {
                  "device_id": "soil-07",
                  "registered_before_placements": false,
                  "items": [
                    {
                      "device_id": "soil-07",
                      "version": 2,
                      "mobility": "fixed",
                      "key_protection": "hardware",
                      "gnss": false,
                      "growing_area": "VN-TG-CL-0042",
                      "lat": 10.3512345,
                      "lon": 106.1234567,
                      "accuracy_m": 3.5,
                      "fix_at": 1790100000.0,
                      "installed_at": 1790100600.0,
                      "installer": "Nguyen Van A",
                      "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
                      "depth_cm": 30.0,
                      "sensor_serial": "RS485-4IN1-00172",
                      "note": "Moved to block B after replanting",
                      "removed_at": null,
                      "recorded_at": 1790101000.0,
                      "valid_until": null
                    },
                    {
                      "device_id": "soil-07",
                      "version": 1,
                      "mobility": "fixed",
                      "key_protection": "hardware",
                      "gnss": false,
                      "growing_area": "VN-TG-CL-0042",
                      "lat": 10.3509876,
                      "lon": 106.1229876,
                      "accuracy_m": 4.0,
                      "fix_at": 1780000000.0,
                      "installed_at": 1780000600.0,
                      "installer": "Nguyen Van A",
                      "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
                      "depth_cm": 30.0,
                      "sensor_serial": "RS485-4IN1-00172",
                      "note": null,
                      "removed_at": null,
                      "recorded_at": 1790101000.0,
                      "valid_until": 1790100600.0
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this company: a device of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: soil-07",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "recordDevicePlacement",
        "summary": "Record a device placement (platform)",
        "description": "SENS-A2 (#225): a platform admin, acting for the device's company (X-Tenant), records a new placement version: when approving the device (#201; a device is approved only while its current version is an installation, else the approval answers 409 `placement_required`), whenever it is moved, and when it is taken out. The prior version is kept; nothing is ever overwritten. A `fixed` placement binds the device to one growing area of the company and records the surveyed install point and the commissioning record (the installer's photo, uploaded first with PUT /v1/attachments/{sha256}, the GPS fix time, the install time and the installer). A body with `removed_at` (a `DevicePlacementRemoval`) records that the device was taken out: the new version ends the binding of the installation before it and keeps its `mobility`, `key_protection` and `gnss`. Audited (`device.placement`) in the company's activity log. Allowed for platform_admin only (never an OAuth client). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "soil-07"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/DevicePlacementCreate"
                  },
                  {
                    "$ref": "#/components/schemas/DevicePlacementRemoval"
                  }
                ]
              },
              "examples": {
                "installation": {
                  "summary": "A fixed device installed (or moved)",
                  "value": {
                    "mobility": "fixed",
                    "key_protection": "hardware",
                    "growing_area": "VN-TG-CL-0042",
                    "lat": 10.3512345,
                    "lon": 106.1234567,
                    "accuracy_m": 3.5,
                    "fix_at": 1790100000.0,
                    "installed_at": 1790100600.0,
                    "installer": "Nguyen Van A",
                    "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
                    "depth_cm": 30.0,
                    "sensor_serial": "RS485-4IN1-00172",
                    "note": "Moved to block B after replanting"
                  }
                },
                "removal": {
                  "summary": "The device taken out",
                  "value": {
                    "removed_at": 1790200000.0,
                    "note": "Taken out for repair"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new placement version.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DevicePlacement"
                },
                "example": {
                  "device_id": "soil-07",
                  "version": 2,
                  "mobility": "fixed",
                  "key_protection": "hardware",
                  "gnss": false,
                  "growing_area": "VN-TG-CL-0042",
                  "lat": 10.3512345,
                  "lon": 106.1234567,
                  "accuracy_m": 3.5,
                  "fix_at": 1790100000.0,
                  "installed_at": 1790100600.0,
                  "installer": "Nguyen Van A",
                  "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
                  "depth_cm": 30.0,
                  "sensor_serial": "RS485-4IN1-00172",
                  "note": "Moved to block B after replanting",
                  "removed_at": null,
                  "recorded_at": 1790101000.0,
                  "valid_until": null,
                  "recorded_by": "support@croppath.example"
                }
              }
            }
          },
          "400": {
            "description": "An unknown or malformed field (a time before 2020 or more than 300 s ahead included; a GPS fix more than 7 days before the install or after it), a removal with any field but `removed_at` and `note`, a fixed placement without its growing area, install point or commissioning record, a growing area that is not the company's, a photo the company's records do not hold as a JPEG or PNG, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "fixed_incomplete": {
                    "value": {
                      "error": "fixed placement incomplete: needs growing_area, photo_sha256",
                      "code": "fixed_placement_incomplete"
                    }
                  },
                  "unknown_growing_area": {
                    "value": {
                      "error": "unknown growing_area",
                      "code": "unknown_growing_area"
                    }
                  },
                  "unknown_photo": {
                    "value": {
                      "error": "unknown photo_sha256: upload the photo (JPEG or PNG) first",
                      "code": "unknown_photo_sha256"
                    }
                  },
                  "install_point": {
                    "value": {
                      "error": "invalid install point: lat, lon and accuracy_m together",
                      "code": "invalid_install_point"
                    }
                  },
                  "fix_time": {
                    "value": {
                      "error": "invalid fix_at: at most 7 days before installed_at and never after it",
                      "code": "invalid_fix_at"
                    }
                  },
                  "removal_fields": {
                    "value": {
                      "error": "invalid removal: removed_at and note only",
                      "code": "invalid_removal"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), or company read-only (the company is leaving CropPath or has left; nothing changes).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this company: a device of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: soil-07",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The new version would start (`installed_at`, or `removed_at` for a removal) before the device's current one, or a removal has no installation to end (no version yet, or the current version is a removal already). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "out_of_order": {
                    "value": {
                      "error": "placement out of order: it starts before the current placement",
                      "code": "placement_out_of_order"
                    }
                  },
                  "nothing_to_remove": {
                    "value": {
                      "error": "no placement to remove: the device has no installation in force",
                      "code": "no_placement_to_remove"
                    }
                  },
                  "idempotency_in_progress": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices/{id}/calibrations": {
      "get": {
        "operationId": "listDeviceCalibrations",
        "summary": "A device's calibrations",
        "description": "SENS-B1d (#234): every calibration recorded for a device of the company, newest first, with the one that supersedes each (`superseded_by`). `sensor_serial` lists one probe's only. Same roles as reading the device; an operator reads only devices of its facilities. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "soil-07"
          },
          {
            "name": "sensor_serial",
            "in": "query",
            "required": false,
            "description": "Only the calibrations of this probe serial (1 to 100 characters).",
            "schema": {
              "type": "string",
              "minLength": 1,
              "maxLength": 100
            },
            "example": "RS485-4IN1-00172"
          }
        ],
        "responses": {
          "200": {
            "description": "The device's calibrations.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Calibrations"
                },
                "example": {
                  "device_id": "soil-07",
                  "items": [
                    {
                      "id": 12,
                      "device_id": "soil-07",
                      "sensor_serial": "RS485-4IN1-00172",
                      "capability": "soil.ph",
                      "calibrated_at": 1790000000.0,
                      "method": "ph_buffers",
                      "reference_values": {
                        "buffers_ph": [
                          4.01,
                          7.0,
                          10.01
                        ]
                      },
                      "coefficients": {
                        "offset": -0.03,
                        "slope": 0.987
                      },
                      "performer": "Can Tho soil laboratory",
                      "accreditation": "iso17025_lab",
                      "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
                      "valid_until": 1805552000.0,
                      "supersedes": null,
                      "created_at": 1790001000.0,
                      "created_by": "admin@coop.example",
                      "superseded_by": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A bad `sensor_serial` or X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "sensor_serial": {
                    "value": {
                      "error": "bad sensor_serial",
                      "code": "bad_sensor_serial"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this company: a device of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: soil-07",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "recordDeviceCalibration",
        "summary": "Record a device calibration",
        "description": "SENS-B1d (#234): a company admin, or a platform admin acting for the company (X-Tenant), records a calibration of one of the company's devices, with its certificate (uploaded first with PUT /v1/attachments/{sha256}, or sent in `certificate`). Calibrations are append-only: a correction is a new calibration that names the one it corrects (`supersedes`); the corrected one is kept. Audited (`device.calibration`) in the company's activity log. Allowed for tenant_admin and platform_admin (and an API client with `device_admin`). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_admin"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "soil-07"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CalibrationCreate"
              },
              "example": {
                "sensor_serial": "RS485-4IN1-00172",
                "capability": "soil.ph",
                "calibrated_at": 1790000000.0,
                "method": "ph_buffers",
                "reference_values": {
                  "buffers_ph": [
                    4.01,
                    7.0,
                    10.01
                  ]
                },
                "coefficients": {
                  "offset": -0.03,
                  "slope": 0.987
                },
                "performer": "Can Tho soil laboratory",
                "accreditation": "iso17025_lab",
                "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
                "valid_until": 1805552000.0
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The calibration recorded.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Calibration"
                },
                "example": {
                  "id": 12,
                  "device_id": "soil-07",
                  "sensor_serial": "RS485-4IN1-00172",
                  "capability": "soil.ph",
                  "calibrated_at": 1790000000.0,
                  "method": "ph_buffers",
                  "reference_values": {
                    "buffers_ph": [
                      4.01,
                      7.0,
                      10.01
                    ]
                  },
                  "coefficients": {
                    "offset": -0.03,
                    "slope": 0.987
                  },
                  "performer": "Can Tho soil laboratory",
                  "accreditation": "iso17025_lab",
                  "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
                  "valid_until": 1805552000.0,
                  "supersedes": null,
                  "created_at": 1790001000.0,
                  "created_by": "admin@coop.example",
                  "superseded_by": null
                }
              }
            }
          },
          "400": {
            "description": "An unknown, missing or malformed field (a `calibrated_at` before 2020 or more than 300 s ahead, a `valid_until` not after it or more than about five years later, a value outside an enum, JSON values too large, too deep or with a number that is not finite, a capability outside the vocabulary that is not an `x-` extension), a certificate whose bytes do not hash to `certificate_sha256` (`certificate_hash_mismatch`) or are not its media type, a `certificate_sha256` the company's uploads do not hold as a PDF, JPEG or PNG when no certificate is sent, a `supersedes` that is not a calibration of this device, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "missing_field": {
                    "value": {
                      "error": "missing field: valid_until",
                      "code": "missing_field"
                    }
                  },
                  "valid_until": {
                    "value": {
                      "error": "invalid valid_until: after calibrated_at",
                      "code": "invalid_valid_until"
                    }
                  },
                  "hash_mismatch": {
                    "value": {
                      "error": "certificate hash mismatch: the certificate does not hash to certificate_sha256",
                      "code": "certificate_hash_mismatch"
                    }
                  },
                  "unknown_certificate": {
                    "value": {
                      "error": "unknown certificate_sha256: upload the certificate (PDF, JPEG or PNG) first",
                      "code": "unknown_certificate_sha256"
                    }
                  },
                  "unknown_supersedes": {
                    "value": {
                      "error": "unknown supersedes: not a calibration of this device",
                      "code": "unknown_supersedes"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), or company read-only (the company is leaving CropPath or has left; nothing changes).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this company: a device of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: soil-07",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The calibration named by `supersedes` is superseded already (correct the one that superseded it). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "superseded": {
                    "value": {
                      "error": "calibration superseded: correct the record that superseded it",
                      "code": "calibration_superseded"
                    }
                  },
                  "idempotency_in_progress": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/devices/{id}/metadata": {
      "get": {
        "operationId": "getDeviceMetadata",
        "summary": "A device's metadata",
        "description": "SENS-B1d (#234): a device's placement version in force (#225) and its calibrations not superseded: the document an EPCIS `deviceMetadata` link of the device's readings can name later (`/v1/devices/{id}/metadata` on this deployment's origin). For the device's company (the roles that read the device; an operator only for devices of its facilities) and platform admins acting for it; never public, and another company's device answers 404. `recorded_by` of the placement is returned to platform admins only. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "device_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Device id.",
            "schema": {
              "type": "string"
            },
            "example": "soil-07"
          }
        ],
        "responses": {
          "200": {
            "description": "The device's metadata.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeviceMetadata"
                },
                "example": {
                  "device_id": "soil-07",
                  "placement": {
                    "device_id": "soil-07",
                    "version": 2,
                    "mobility": "fixed",
                    "key_protection": "hardware",
                    "gnss": false,
                    "growing_area": "VN-TG-CL-0042",
                    "lat": 10.3512345,
                    "lon": 106.1234567,
                    "accuracy_m": 3.5,
                    "fix_at": 1790100000.0,
                    "installed_at": 1790100600.0,
                    "installer": "Nguyen Van A",
                    "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
                    "depth_cm": 30.0,
                    "sensor_serial": "RS485-4IN1-00172",
                    "note": "Moved to block B after replanting",
                    "removed_at": null,
                    "recorded_at": 1790101000.0,
                    "valid_until": null
                  },
                  "calibrations": [
                    {
                      "id": 12,
                      "device_id": "soil-07",
                      "sensor_serial": "RS485-4IN1-00172",
                      "capability": "soil.ph",
                      "calibrated_at": 1790000000.0,
                      "method": "ph_buffers",
                      "reference_values": {
                        "buffers_ph": [
                          4.01,
                          7.0,
                          10.01
                        ]
                      },
                      "coefficients": {
                        "offset": -0.03,
                        "slope": 0.987
                      },
                      "performer": "Can Tho soil laboratory",
                      "accreditation": "iso17025_lab",
                      "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
                      "valid_until": 1805552000.0,
                      "supersedes": null,
                      "created_at": 1790001000.0,
                      "created_by": "admin@coop.example",
                      "superseded_by": null
                    }
                  ],
                  "as_of": 1790200000.0
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device for this company: a device of another company, or outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: soil-07",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/approve": {
      "post": {
        "operationId": "approveGateway",
        "summary": "Approve a gateway (platform)",
        "description": "#201: a platform admin approves a gateway of any company, so evidence from it counts as Device-recorded or above. Idempotent: an approved one keeps its first approval. The body lists the waiting keys the platform admin saw in the queue: exactly those are approved with it (the audit row names them, `approved_keys`); a key the company registered since stays pending, so its evidence stays Self-declared and the gateway is listed in the queue again. 409, and nothing changes, when a listed key is no longer waiting (revoked, approved meanwhile, or not this gateway's). Audited (`gateway.approve`) in the gateway's company's activity log. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The gateway id.",
            "schema": {
              "type": "string"
            },
            "example": "gw-7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DeviceApproval"
              },
              "example": {
                "keys": [
                  "gw-7-k1"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The gateway with its approval.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeviceApprovalItem"
                },
                "example": {
                  "kind": "gateway",
                  "id": "gw-7",
                  "tenant": "coop-dl",
                  "tenant_name": "Coop DL",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "profile": null,
                  "display_name": "Packing hall gateway",
                  "registered_by": "admin@coop.example",
                  "registered_at": 1790000000.5,
                  "approval": "approved",
                  "approval_reason": null,
                  "approval_at": 1790000200.0,
                  "approval_by": "support@croppath.example",
                  "keys": []
                }
              }
            }
          },
          "400": {
            "description": "An unknown field, a missing or malformed keys list, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_keys": {
                    "value": {
                      "error": "invalid keys: a list of up to 100 distinct key ids",
                      "code": "invalid_keys"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the gateway's company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway in any company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "A listed key is no longer waiting for approval (revoked, approved meanwhile, or not this gateway's): reload the queue. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key_not_waiting_for_approval": {
                    "value": {
                      "error": "key not waiting for approval",
                      "code": "key_not_waiting_for_approval"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/reject": {
      "post": {
        "operationId": "rejectGateway",
        "summary": "Reject a gateway (platform)",
        "description": "#201: a platform admin rejects a gateway of any company, pending or approved (withdrawing its approval), with a reason shown to the company. Evidence from it then counts as Self-declared: open lots are lowered at their recompute, a sealed lot's tier can only be lowered. 409 when it is already rejected. Audited (`gateway.reject`) in the gateway's company's activity log. Allowed for platform_admin only (never an OAuth client).",
        "tags": [
          "devices"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The gateway id.",
            "schema": {
              "type": "string"
            },
            "example": "gw-7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DeviceRejection"
              },
              "example": {
                "reason": "The gateway is not installed at the registered packing house."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The gateway with its approval.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeviceApprovalItem"
                },
                "example": {
                  "kind": "gateway",
                  "id": "gw-7",
                  "tenant": "coop-dl",
                  "tenant_name": "Coop DL",
                  "site": "ph1",
                  "facility": "VN-TGPH-021",
                  "profile": null,
                  "display_name": "Packing hall gateway",
                  "registered_by": "admin@coop.example",
                  "registered_at": 1790000000.5,
                  "approval": "rejected",
                  "approval_reason": "Serial number does not match.",
                  "approval_at": 1790000200.0,
                  "approval_by": "support@croppath.example",
                  "keys": []
                }
              }
            }
          },
          "400": {
            "description": "An unknown field (`keys` belongs to an approval), a missing or too long reason, a bad X-Request-Id or Idempotency-Key.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: a string of 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only when the gateway's company is leaving CropPath or has left, whatever company the platform admin acts for; nothing changes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway in any company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: knk-7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The gateway is already rejected. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "gateway_already_rejected": {
                    "value": {
                      "error": "gateway already rejected",
                      "code": "gateway_already_rejected"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/anchors": {
      "get": {
        "operationId": "listPublicAnchors",
        "summary": "Daily integrity anchors",
        "description": "INTEGRITY-2 (#202): the daily anchors of the activity log, the evidence envelopes, the lot seals, the reviews and the envelopes' statuses when anchored, oldest first, a page at a time. Each closed UTC day gets one, an hour after it ends, even when it has no records, chained to the day before; each anchor is time-stamped by the configured RFC 3161 TSA. Download every page and run `python3 verify_anchors.py chain --api <host>` (the script is /developers/downloads/verify_anchors.py) to check the chain and each token (its genTime at most 48 h after its day ended, and a verified token for every day that ended more than 48 h ago; `--allow-unstamped` for a platform without a TSA); keep the pages, and later add `--anchors <saved file>` to check that they are still an unchanged prefix of the chain. Anonymous and tenant-less: the same bytes for every visitor. Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: one statement of at most 101 rows.",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "after",
            "in": "query",
            "required": false,
            "description": "A day (YYYY-MM-DD): the page starts after it. Pass the previous page's `next_after`.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2026-10-07"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "Page size, 1 to 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 30
            },
            "example": 30
          }
        ],
        "responses": {
          "200": {
            "description": "One page of anchors.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrityAnchorPage"
                },
                "example": {
                  "version": 1,
                  "genesis": "0000000000000000000000000000000000000000000000000000000000000000",
                  "items": [
                    {
                      "day": "2026-10-08",
                      "seq": 41,
                      "version": 1,
                      "prev_anchor": "be49fb23ac82b5ec39175d41c24be9962da541a3e6e3e942e065c9b1f85a977d",
                      "audit_root": "69517c75b68faea3ae84cb5116c7d12125d32e23529a1ff6ef36f666ce0fd882",
                      "evidence_root": "a59ba7faac45b5663de69c9050f21fc04ee99a39fba52cebc08003fc009b9b69",
                      "seal_root": "b161f22a5c2003f3d72b16a782971049af1c3686cfa1395b65238616c7854c6d",
                      "review_root": "7f2c1c56a4cbbd0d6e3c4f5c2b5d1b6a0f3e7a9c8d2e4b1f6a3c5d7e9f0b2a4c",
                      "held_root": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
                      "day_root": "ad8af655fbd5987cb1634e88fa4997bfd23f0e106632e639ec35c8195f4d9deb",
                      "audit_count": 1840,
                      "evidence_count": 9312,
                      "seal_count": 3,
                      "review_count": 2,
                      "held_count": 0,
                      "anchor": "b54619909ae9f243ff09bd33eeab7103c8979cc0a354952304c2e12580ccb899",
                      "created_at": "2026-10-09T01:00:04Z",
                      "timestamp": {
                        "status": "verified",
                        "gen_time": "2026-10-09T01:00:06Z",
                        "token": "MIIGTwYJKoZIhvcNAQcCoIIGQDCCBjwCAQMxDzANBglghkgBZQMEAgEFADCB"
                      }
                    }
                  ],
                  "next_after": null
                }
              }
            }
          },
          "400": {
            "description": "`after` is not a day or `limit` is out of range (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "after": {
                    "value": {
                      "error": "bad after",
                      "code": "bad_after"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/lots/{publicId}/anchor-proof": {
      "get": {
        "operationId": "getPublicLotAnchorProof",
        "summary": "Inclusion proof of a public lot's seal or event",
        "description": "INTEGRITY-2 (#202): proves that a public lot's seal (no `event`), or one of its events, is among the records of its day's anchor, as stored today: the record, its leaf hash, its RFC 9162 audit path and the day's anchor. `event` names one of the sealed lot's accepted event envelopes (the events of its EPCIS document, GET /v1/public/lots/{publicId}/epcis.jsonld), by id or as its eventID `urn:uuid:<id>`. Check it with `python3 verify_anchors.py proof --api <host> --lot <publicId> [--event <id>]`, which also compares the anchor with the published chain (the script is /developers/downloads/verify_anchors.py). Anonymous and tenant-less like the public lot record. Not audited (a read); it changes nothing. Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Bounded work: the public lot's lookup, the record, the day's anchor, and its stored leaves unless the day's tree is already in memory (a bounded cache).",
        "tags": [
          "public"
        ],
        "security": [],
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          },
          {
            "name": "event",
            "in": "query",
            "required": false,
            "description": "One of the sealed lot's event ids (or `urn:uuid:<id>`); without it the seal is proven.",
            "schema": {
              "type": "string",
              "maxLength": 137
            },
            "example": "9b2f6c1e-4d3a-4b8e-9f0a-1c2d3e4f5a6b"
          }
        ],
        "responses": {
          "200": {
            "description": "The proof.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnchorInclusionProof"
                },
                "example": {
                  "kind": "seal",
                  "day": "2026-10-08",
                  "record": {
                    "manifest_sha256": "0000000000000000000000000000000000000000000000000000000000001efa",
                    "sealed_at": 1791440400.25,
                    "fruit_count": 13,
                    "event_count": 41
                  },
                  "leaf_hash": "52b42e8bff3ec1d57e4813b951e084464611dd15d449f20ae82936fc7e1f70c2",
                  "included": true,
                  "leaf_index": 1,
                  "tree_size": 3,
                  "path": [
                    "03c144ed8ca7f54eedbabe5204716a751defce4c61ad32756454df2d44cc6b06",
                    "a9a8a7268b3840b423803a0ea58206e4eac69b1055a063a35b97ed5815705930"
                  ],
                  "anchor": {
                    "day": "2026-10-08",
                    "seq": 41,
                    "version": 1,
                    "prev_anchor": "be49fb23ac82b5ec39175d41c24be9962da541a3e6e3e942e065c9b1f85a977d",
                    "audit_root": "69517c75b68faea3ae84cb5116c7d12125d32e23529a1ff6ef36f666ce0fd882",
                    "evidence_root": "a59ba7faac45b5663de69c9050f21fc04ee99a39fba52cebc08003fc009b9b69",
                    "seal_root": "b161f22a5c2003f3d72b16a782971049af1c3686cfa1395b65238616c7854c6d",
                    "review_root": "7f2c1c56a4cbbd0d6e3c4f5c2b5d1b6a0f3e7a9c8d2e4b1f6a3c5d7e9f0b2a4c",
                    "held_root": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
                    "day_root": "ad8af655fbd5987cb1634e88fa4997bfd23f0e106632e639ec35c8195f4d9deb",
                    "audit_count": 1840,
                    "evidence_count": 9312,
                    "seal_count": 3,
                    "review_count": 2,
                    "held_count": 0,
                    "anchor": "b54619909ae9f243ff09bd33eeab7103c8979cc0a354952304c2e12580ccb899",
                    "created_at": "2026-10-09T01:00:04Z",
                    "timestamp": {
                      "status": "verified",
                      "gen_time": "2026-10-09T01:00:06Z",
                      "token": "MIIGTwYJKoZIhvcNAQcCoIIGQDCCBjwCAQMxDzANBglghkgBZQMEAgEFADCB"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "`event` is malformed (`Cache-Control: no-store`), or the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad event",
                  "code": "bad_event"
                }
              }
            }
          },
          "404": {
            "description": "Not a public lot, a lot that is not sealed, an `event` that is not one of the sealed lot's events, or a record whose day is not anchored yet (a day is anchored an hour after it ends): every such request gets this same body and headers.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/epoch": {
      "get": {
        "operationId": "getPublicEpoch",
        "summary": "The current server epoch value",
        "description": "SENS-B2c (#239): the newest signed server epoch value. The backend issues a new one every hour, signed with a key of its own (ES256, never a device, gateway, lab or issuer key). A device puts the `epoch` it last fetched in `context.epoch` of the envelopes it signs (optional; /developers/downloads/envelope-v1.schema.json): a reading cannot have been signed before the value it cites was issued, so its creation time is bounded on both sides (the server records when it received it). Ingest flags, and never rejects or quarantines, an envelope whose value the server never issued, was issued after a reading's time (beyond the clock allowance), or is older than the allowed window (24 hours by default) at a reading's time: each flagged reading is Self-declared (reason `server_epoch_mismatch`) and the company gets a `server_epoch_mismatch` alert. To verify a value: the ES256 signature `sig.value` (base64url of r || s) over the canonical JSON (the envelopes' rule) of the document without `sig` and `publicKeyJwk`, with the epoch key's public key (`publicKeyJwk`; compare it with a copy you trust). Old values are public, so this proves data was not prepared in advance, not that it was not back-filled later. Anonymous and tenant-less: the same bytes for every visitor. Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Not part of the partner SDK clients (`x-not-in-sdk`). Bounded work: one indexed statement.",
        "tags": [
          "public"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The newest value, issued at most two hours ago.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ServerEpoch"
                },
                "example": {
                  "epoch": "3f9a1c0e7b2d4e6f8a0b1c2d3e4f5a6b",
                  "issuedAt": "2026-10-16T03:00:02.418Z",
                  "kid": "epoch-f1d59449b727165d",
                  "sig": {
                    "alg": "ES256",
                    "kid": "epoch-f1d59449b727165d",
                    "value": "WeU8uTYHd3NOSB1v4B45m7JXKGhm9GcGF9-KkecUmTq9x0d7XB92o45NQS5-DgW0HW5TqGDKWtpMuVl27oPj4Q"
                  },
                  "publicKeyJwk": {
                    "kty": "EC",
                    "crv": "P-256",
                    "x": "UVw9brnjlrkE0_7Kf1T9zQzB6Ze_N13KUVrQpsO0A18",
                    "y": "RTa-OlDzGPv5pUdZAqIhUCvvDVfgjFOyzApW8X2fk1Q"
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "No value was issued in the last two hours: no epoch key is configured (AGRITRACE_EPOCH_KEY), or the process that issues the values has stopped. Never cached; retry later.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "server epoch value unavailable",
                  "code": "server_epoch_value_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/public/lots/{publicId}/corrections": {
      "get": {
        "operationId": "getPublicLotCorrections",
        "summary": "Corrections of a public lot before its seal",
        "description": "INTEGRITY-4 (#204): how often each journey step of a public lot was corrected before its seal, from the append-only activity log (the public lot page states it beside each step). A correction is a successful edit recorded in the company's activity log before the lot was sealed: a lot edit (`PATCH /v1/lots/{lot}`, the `lot.update` row) that changed the value of a field a step shows (a field sent with its current value is no correction; growing area: `registration`; harvest date or harvest event: `harvest`; variety, product or GTIN: `details`, the lot's own details; the destination is never public and never counted), or an operator's action on a fruit (`POST /v1/fruits/{code}/actions`, the `fruit.action` row) that overrides its level, rejects it or has it re-measured: `measurement` (an acceptance and a replayed action are not corrections). Only counts and local dates are answered: never who corrected, what the value was before or after, the reason, a field name or the request. A record can change only while its lot is open, so every correction precedes the seal. `measurement` counts the corrections of every fruit of the lot. `after_public` counts those made after the lot was first public (its first measurement session opened, which makes the lot `open`, the first status the public pages show); the page highlights them. A `measurement` correction made while the fruit's own measurement session was running (from its opening to its close, less any time it was paused) is part of measuring that fruit and is not in `after_public`, only in `count`; one made at any other time is (after the session closed, while it was paused, or while only another session of the lot was running). A step without a correction is left out. Anonymous and tenant-less like the public records (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Not part of the partner SDK clients (`x-not-in-sdk`). Bounded work: the answer is stored with the lot's materialized public read model (#141) and invalidated with it, so a valid one is one statement; otherwise the lot's lookup and at most four statements, one of which reads the lot's fruits.",
        "tags": [
          "public"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The lot's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "074eb09b371fc71c380da235aea9c14a"
          }
        ],
        "responses": {
          "200": {
            "description": "The corrections, per step.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicCorrections"
                },
                "example": {
                  "sealed": true,
                  "public_since": "2026-09-27",
                  "steps": [
                    {
                      "kind": "harvest",
                      "count": 1,
                      "last_on": "2026-09-27",
                      "after_public": 0
                    },
                    {
                      "kind": "measurement",
                      "count": 3,
                      "last_on": "2026-09-28",
                      "after_public": 3
                    }
                  ]
                }
              }
            }
          },
          "404": {
            "description": "Not a public lot: an unknown or malformed id, a lot that is not open or closed, not of a crop of the crop registry (#156), or lacks a field the record needs. Every such id gets this same body and headers; the id is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lots",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/public/fruits/{publicId}/corrections": {
      "get": {
        "operationId": "getPublicFruitCorrections",
        "summary": "Corrections a public fruit's page states",
        "description": "INTEGRITY-4 (#204): the corrections a public fruit's page states beside its journey steps: its lot's edits as `GET /v1/public/lots/{publicId}/corrections` counts them, and, for `measurement`, the corrections of this fruit alone. Answered under exactly the public fruit record's visibility; logs no scan. A correction is a successful edit recorded in the company's activity log before the lot was sealed: a lot edit (`PATCH /v1/lots/{lot}`, the `lot.update` row) that changed the value of a field a step shows (a field sent with its current value is no correction; growing area: `registration`; harvest date or harvest event: `harvest`; variety, product or GTIN: `details`, the lot's own details; the destination is never public and never counted), or an operator's action on a fruit (`POST /v1/fruits/{code}/actions`, the `fruit.action` row) that overrides its level, rejects it or has it re-measured: `measurement` (an acceptance and a replayed action are not corrections). Only counts and local dates are answered: never who corrected, what the value was before or after, the reason, a field name or the request. A record can change only while its lot is open, so every correction precedes the seal. Anonymous and tenant-less like the public records (no session, token, cookie or X-Tenant changes the answer). Not audited (a read). Rate limited per client before anything else (/v1/public/*: bursts of 60, then 20 a second). Not part of the partner SDK clients (`x-not-in-sdk`). Bounded work: the public fruit record's two lookups, then at most four statements, none growing with the lot.",
        "tags": [
          "public"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "publicId",
            "in": "path",
            "required": true,
            "description": "The fruit's public id (128 random bits as hex). Any other value is 404 like an unknown id.",
            "schema": {
              "type": "string"
            },
            "example": "73879f17d0930440809333f141385eb6"
          }
        ],
        "responses": {
          "200": {
            "description": "The corrections, per step.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60, stale-while-revalidate=300` (#177: the edge keeps it 60 s, the frontend's staleTime, and may serve it stale up to 300 s more while it refetches; browsers always revalidate). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PublicCorrections"
                },
                "example": {
                  "sealed": true,
                  "public_since": "2026-09-27",
                  "steps": [
                    {
                      "kind": "harvest",
                      "count": 1,
                      "last_on": "2026-09-27",
                      "after_public": 0
                    },
                    {
                      "kind": "measurement",
                      "count": 3,
                      "last_on": "2026-09-28",
                      "after_public": 3
                    }
                  ]
                }
              }
            }
          },
          "404": {
            "description": "Not a public fruit: an unknown or malformed id, a fruit that is not recorded or overridden, a fruit of a lot that is not public or has no growing area, or one lacking a field the record needs. Every such id gets this same body and headers, logs no scan, and is never echoed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (#177: a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: fruits",
                  "code": "not_found"
                }
              }
            }
          },
          "410": {
            "$ref": "#/components/responses/LotRemoved"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many /v1/public/* requests from this client address (per-IP token bucket: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer; a request from a trusted proxy that carries the internal `X-Agritrace-Scan-Key` (the web server's own render) is counted against the visitor address it forwards in `cf-connecting-ip` (sent once, a valid IP address). Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/help": {
      "get": {
        "operationId": "getHelp",
        "summary": "What the staff shell's Help shows: announcements and the status page",
        "description": "SELF-2-7 (#196). The platform announcements showing now (the staff shell's banner; never shown on a public page) and CropPath's status page address (AGRITRACE_STATUS_PAGE_URL; null when the deployment has none, and the console hides the link). Any signed-in user, whatever the roles.",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The announcements and the status page.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`private, no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Help"
                },
                "example": {
                  "status_page_url": "https://status.croppath.example",
                  "announcements": [
                    {
                      "id": 3,
                      "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
                      "level": "warning",
                      "starts_at": 1790000000.5,
                      "ends_at": 1790086400.5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant). Session routes are open to every role.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "tenant not allowed",
                  "code": "tenant_not_allowed"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/support-requests": {
      "get": {
        "operationId": "listSupportRequests",
        "summary": "List the company's support requests",
        "description": "SELF-2-7 (#196). The selected company's (X-Tenant) support requests, newest first, with their status and CropPath's reply: every request of the company for tenant_admin and platform_admin, only the caller's own for operators and auditors. Allowed for only tenant_admin, operator, auditor and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused; lab users are refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of requests.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SupportRequestPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 12,
                      "tenant": "coop-dl",
                      "user": {
                        "id": 7,
                        "email": "op@coop.example",
                        "display_name": "Lan"
                      },
                      "subject": "Scale at line A1 shows no weight",
                      "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
                      "record_id": "LOT-2026-001",
                      "status": "answered",
                      "reply": "Please restart the scale; it reconnects in a minute.",
                      "created_at": 1790000000.5,
                      "updated_at": 1790003600.5
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, operator, auditor and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused; lab users are refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createSupportRequest",
        "summary": "Send CropPath a support request",
        "description": "SELF-2-7 (#196). Sends CropPath a request from the caller in the selected company (X-Tenant): a subject, a text and optionally the id of the record it is about. It lands in the platform's queue with the company and the user; there is no email, so the answer comes back as the request's status and reply. Stored as plain text exactly as typed (trimmed), never as HTML or markdown. At most 5 requests per person per hour, 10 per person per day and 30 per company per day (429). Audited (`support_request.create`, in the same transaction; never the text). Allowed for only tenant_admin, operator, auditor and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused; lab users are refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SupportRequestCreate"
              },
              "example": {
                "subject": "Scale at line A1 shows no weight",
                "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
                "record_id": "LOT-2026-001"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The request, as the company sees it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SupportRequest"
                },
                "example": {
                  "id": 12,
                  "tenant": "coop-dl",
                  "user": {
                    "id": 7,
                    "email": "op@coop.example",
                    "display_name": "Lan"
                  },
                  "subject": "Scale at line A1 shows no weight",
                  "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
                  "record_id": "LOT-2026-001",
                  "status": "open",
                  "reply": null,
                  "created_at": 1790000000.5,
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a value outside the limits, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "subject": {
                    "value": {
                      "error": "invalid subject: required, text of at most 200 characters",
                      "code": "invalid_subject"
                    }
                  },
                  "body": {
                    "value": {
                      "error": "invalid body: required, text of at most 5000 characters",
                      "code": "invalid_body"
                    }
                  },
                  "record_id": {
                    "value": {
                      "error": "invalid record_id: at most 100 letters, digits and . _ : / # -, such as LOT-2026-001",
                      "code": "invalid_record_id"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown field: priority",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, operator, auditor and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused; lab users are refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only once the company has left CropPath; during its 30-day read-only window this stays open (owner decision A).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "429": {
            "description": "Too many requests sent: at most 5 per person per hour, 10 per person per day and 30 per company per day. Nothing was stored; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many support requests: at most 5 per person per hour",
                  "code": "too_many_support_requests"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/support-requests/{id}": {
      "get": {
        "operationId": "getSupportRequest",
        "summary": "Read one of the company's support requests",
        "description": "SELF-2-7 (#196). One support request of the selected company (X-Tenant): any of the company's for tenant_admin and platform_admin, only the caller's own for operators and auditors. Another company's request, or another person's for an operator or auditor, answers 404 like a missing one. Allowed for only tenant_admin, operator, auditor and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused; lab users are refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The request id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          }
        ],
        "responses": {
          "200": {
            "description": "The request.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SupportRequest"
                },
                "example": {
                  "id": 12,
                  "tenant": "coop-dl",
                  "user": {
                    "id": 7,
                    "email": "op@coop.example",
                    "display_name": "Lan"
                  },
                  "subject": "Scale at line A1 shows no weight",
                  "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
                  "record_id": "LOT-2026-001",
                  "status": "answered",
                  "reply": "Please restart the scale; it reconnects in a minute.",
                  "created_at": 1790000000.5,
                  "updated_at": 1790003600.5
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, operator, auditor and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused; lab users are refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No request with this id that the caller may read (another company's, or another person's).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/platform/support-requests": {
      "get": {
        "operationId": "listPlatformSupportRequests",
        "summary": "List every company's support requests (the platform's queue)",
        "description": "SELF-2-7 (#196). Every company's support requests, newest first; `status` and `tenant` narrow the queue. Allowed for only platform_admin, through a signed-in session: an API token or the legacy token is refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only requests in this status.",
            "schema": {
              "type": "string",
              "enum": [
                "open",
                "in_progress",
                "answered",
                "closed"
              ]
            },
            "example": "open"
          },
          {
            "name": "tenant",
            "in": "query",
            "required": false,
            "description": "Only this company's requests.",
            "schema": {
              "type": "string"
            },
            "example": "coop-dl"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of the queue.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PlatformSupportRequestPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 12,
                      "tenant": "coop-dl",
                      "user": {
                        "id": 7,
                        "email": "op@coop.example",
                        "display_name": "Lan"
                      },
                      "subject": "Scale at line A1 shows no weight",
                      "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
                      "record_id": "LOT-2026-001",
                      "status": "answered",
                      "reply": "Please restart the scale; it reconnects in a minute.",
                      "created_at": 1790000000.5,
                      "updated_at": 1790003600.5,
                      "updated_by": "support@croppath.example"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `status`, `tenant`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "value": {
                      "error": "invalid status: one of open, in_progress, answered, closed",
                      "code": "invalid_status"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "invalid tenant",
                      "code": "invalid_tenant"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin, through a signed-in session: an API token or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/platform/support-requests/{id}": {
      "patch": {
        "operationId": "updatePlatformSupportRequest",
        "summary": "Change a support request's status or reply",
        "description": "SELF-2-7 (#196). CropPath sets a request's status and/or its reply (plain text; null or blank clears it); the company then sees both in its Help panel. Audited (`support_request.update`, in the same transaction, in the request's company's activity log; never the reply's text). Allowed for only platform_admin, through a signed-in session: an API token or the legacy token is refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The request id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SupportRequestUpdate"
              },
              "example": {
                "status": "answered",
                "reply": "Please restart the scale; it reconnects in a minute."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The request, as the queue shows it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PlatformSupportRequest"
                },
                "example": {
                  "id": 12,
                  "tenant": "coop-dl",
                  "user": {
                    "id": 7,
                    "email": "op@coop.example",
                    "display_name": "Lan"
                  },
                  "subject": "Scale at line A1 shows no weight",
                  "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
                  "record_id": "LOT-2026-001",
                  "status": "answered",
                  "reply": "Please restart the scale; it reconnects in a minute.",
                  "created_at": 1790000000.5,
                  "updated_at": 1790003600.5,
                  "updated_by": "support@croppath.example"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, nothing to change, an unknown field or a bad value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "nothing": {
                    "value": {
                      "error": "nothing to change: send a status, a reply or both",
                      "code": "nothing_to_change"
                    }
                  },
                  "status": {
                    "value": {
                      "error": "invalid status: one of open, in_progress, answered, closed",
                      "code": "invalid_status"
                    }
                  },
                  "reply": {
                    "value": {
                      "error": "invalid reply: text of at most 5000 characters",
                      "code": "invalid_reply"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown field: note",
                      "code": "unknown_field"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin, through a signed-in session: an API token or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only once the request's company has left CropPath, whatever company the platform admin acts for; nothing changes. During that company's 30-day read-only window CropPath can still reply (owner decision A).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No support request with this id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/platform/announcements": {
      "get": {
        "operationId": "listAnnouncements",
        "summary": "List the platform announcements",
        "description": "SELF-2-7 (#196). Every announcement, newest first, each live, scheduled or ended. Allowed for only platform_admin, through a signed-in session: an API token or the legacy token is refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of announcements.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnnouncementPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
                      "level": "warning",
                      "starts_at": 1790000000.5,
                      "ends_at": 1790086400.5,
                      "state": "live",
                      "created_at": 1790000000.5,
                      "created_by": "support@croppath.example",
                      "expired_at": null,
                      "expired_by": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin, through a signed-in session: an API token or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createAnnouncement",
        "summary": "Post a platform announcement for the staff shell",
        "description": "SELF-2-7 (#196). A short plain-text notice every signed-in user sees as a banner in the staff shell (never on a public page), from `starts_at` until `ends_at` or until expired. At most 20 live or scheduled at once (409). Audited (`announcement.create`, in the same transaction; in no company's activity log). Allowed for only platform_admin, through a signed-in session: an API token or the legacy token is refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnnouncementCreate"
              },
              "example": {
                "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
                "level": "warning",
                "ends_at": 1790086400.5
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The announcement.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Announcement"
                },
                "example": {
                  "id": 3,
                  "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
                  "level": "warning",
                  "starts_at": 1790000000.5,
                  "ends_at": 1790086400.5,
                  "state": "live",
                  "created_at": 1790000000.5,
                  "created_by": "support@croppath.example",
                  "expired_at": null,
                  "expired_by": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a value outside the limits, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "text": {
                    "value": {
                      "error": "invalid text: required, text of at most 500 characters",
                      "code": "invalid_text"
                    }
                  },
                  "level": {
                    "value": {
                      "error": "invalid level: one of info, warning",
                      "code": "invalid_level"
                    }
                  },
                  "ends_at": {
                    "value": {
                      "error": "invalid ends_at: later than the start, and at most a year after it",
                      "code": "invalid_ends_at"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin, through a signed-in session: an API token or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "20 announcements are already live or scheduled; or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "too_many": {
                    "value": {
                      "error": "too many announcements: at most 20 live or scheduled; expire one first",
                      "code": "too_many_announcements"
                    }
                  },
                  "idempotency": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/platform/announcements/{id}/expire": {
      "post": {
        "operationId": "expireAnnouncement",
        "summary": "End a platform announcement now",
        "description": "SELF-2-7 (#196). Stops showing the announcement at once; final. Audited (`announcement.expire`, in the same transaction). Allowed for only platform_admin, through a signed-in session: an API token or the legacy token is refused (403).",
        "tags": [
          "support"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The announcement id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The announcement, ended.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Announcement"
                },
                "example": {
                  "id": 3,
                  "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
                  "level": "warning",
                  "starts_at": 1790000000.5,
                  "ends_at": 1790086400.5,
                  "state": "ended",
                  "created_at": 1790000000.5,
                  "created_by": "support@croppath.example",
                  "expired_at": 1790000600.5,
                  "expired_by": "support@croppath.example"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin, through a signed-in session: an API token or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No announcement with this id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The announcement already ended; or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "ended": {
                    "value": {
                      "error": "announcement already ended",
                      "code": "announcement_already_ended"
                    }
                  },
                  "idempotency": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/platform/overview": {
      "get": {
        "operationId": "getPlatformOverview",
        "summary": "Read the platform overview",
        "description": "#274. What a platform admin monitors across every company on the admin home: the service's health (as `getAdminHealth`), this server's traffic and ingest since it started with their per-minute figures, the queues, the work waiting on CropPath, sign-in security and the companies (at most 50, those that need attention first; names, codes and counts only, no person's data). Computed at most every 30 seconds: the server serves one answer for `max_age_s` seconds after `generated_at`. Read-only and not audited (a read). `no-store`. Allowed for only platform_admin, through a signed-in session: an API token (a platform_admin one included) or the legacy token is refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the console's admin home.",
        "tags": [
          "ops"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The platform overview.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PlatformOverview"
                },
                "example": {
                  "generated_at": "2026-10-17T07:32:05Z",
                  "max_age_s": 30,
                  "process": {
                    "started_at": "2026-10-17T01:02:03Z",
                    "role": "all",
                    "mqtt_ingest": "bridge"
                  },
                  "sections": {
                    "health": {
                      "state": "ok",
                      "read_only": false,
                      "warnings": [],
                      "db": {
                        "dialect": "postgresql",
                        "schema_version": 108,
                        "expected_schema_version": 108,
                        "round_trip_ms": 0.8
                      },
                      "mqtt": {
                        "connected": true,
                        "subscribed": true
                      },
                      "certificates": [
                        {
                          "name": "broker",
                          "not_after": "2027-01-02T00:00:00Z",
                          "days_left": 77
                        }
                      ],
                      "tsa": {
                        "mode": "on",
                        "pending": 0,
                        "failing": 0
                      },
                      "issuer_keys": {
                        "available": true
                      },
                      "anchor_last_day": "2026-10-16",
                      "evidence_archive": {
                        "last_day": "2026-10-15",
                        "status": "archived"
                      },
                      "platform_alerts_open": 0,
                      "platform_alerts_open_high": 0
                    },
                    "traffic": {
                      "state": "ok",
                      "since": "2026-10-17T01:02:03Z",
                      "answers": 18234,
                      "server_errors": 2,
                      "refused_429": 14,
                      "series_since": "2026-10-17T07:28:05Z",
                      "server_errors_per_minute": [
                        0,
                        0,
                        1,
                        0
                      ]
                    },
                    "ingest": {
                      "state": "ok",
                      "since": "2026-10-17T01:02:03Z",
                      "outcomes": {
                        "accepted": 90122,
                        "quarantined": 12,
                        "duplicate": 40,
                        "rejected": 3
                      },
                      "series_since": "2026-10-17T07:28:05Z",
                      "messages_per_minute": [
                        1502,
                        1498,
                        1510
                      ],
                      "backlog": {
                        "messages": 0,
                        "capped": false,
                        "companies": 0,
                        "over_budget": 0
                      }
                    },
                    "queues": {
                      "state": "ok",
                      "outbound": {
                        "epcis": 0
                      },
                      "webhooks_pending": 0,
                      "email": {
                        "queued": 0,
                        "oldest_queued_at": null,
                        "failed_24h": 0
                      },
                      "recall_notices_pending": 0,
                      "exports": {
                        "active": 0,
                        "failed_7d": 0
                      }
                    },
                    "waiting": {
                      "state": "ok",
                      "device_approvals": 1,
                      "gateway_approvals": 0,
                      "key_approvals": 0,
                      "facility_proposals": 2,
                      "boundary_proposals": 0,
                      "support_open": 1,
                      "support_in_progress": 0,
                      "lab_accreditations_expiring": 0,
                      "lab_approvals_expiring": 1,
                      "companies_leaving": 0
                    },
                    "security": {
                      "state": "ok",
                      "failed_sign_ins_24h": 5,
                      "capped": false,
                      "accounts_locked": 0
                    },
                    "companies": {
                      "state": "ok",
                      "total": 1,
                      "items": [
                        {
                          "id": "coop-dl",
                          "name": "HTX Dak Lak",
                          "sandbox": false,
                          "offboarding": null,
                          "members_active": 9,
                          "admins_active": 2,
                          "devices_registered": 42,
                          "messages_last_hour": 9000,
                          "api_calls_today": 1200,
                          "api_day_percent": 0,
                          "open_high_alerts": 2,
                          "support_open": 1
                        }
                      ]
                    },
                    "irrigation": {
                      "state": "ok",
                      "controllers": 14,
                      "online": 12,
                      "not_measured": 1,
                      "controllers_capped": false,
                      "online_rate_7d": [
                        0.98,
                        0.97,
                        0.99,
                        0.99,
                        0.96,
                        0.98,
                        0.99
                      ],
                      "rejects_14d": {
                        "interlock": 1,
                        "manual_override_active": 4
                      },
                      "expired_rate_14d": 0.02,
                      "commands_capped": false,
                      "companies": [
                        {
                          "id": "coop-dl",
                          "open_urgent": 0,
                          "alarms_raised_7d": 18
                        }
                      ],
                      "capped": false,
                      "attention": []
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only platform_admin, through a signed-in session: an API token or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/console/home": {
      "get": {
        "operationId": "getConsoleHome",
        "summary": "Read the console's work home",
        "description": "#286. For the selected company (X-Tenant) and the caller's packing houses: the work home of the console. The open and paused measurement sessions (with whether the caller opened each), the work by next action (lots to measure, to close and sign, with a failed lab result, waiting for the lab, to pack and seal, to label for export, to put on a shipment, recalled in the last 30 days; counted among the newest 1,000 lots of each packing house, `work.window`), the open shipments, the device messages waiting for review, the devices and stations, and today's counts in the Vietnam calendar day. An operator's answer holds only the packing houses of their role (every one of the company when their role names none); a company admin's, and a platform admin's acting for the company, the whole company. Computed at most every 10 seconds per company and set of packing houses: the server serves one answer for `max_age_s` seconds after `generated_at`. Read-only and not audited (a read). `no-store`. Allowed for tenant_admin, platform_admin (acting for the company through X-Tenant) and operator through a signed-in session only: an API token, an API client or the legacy token is refused (403); auditors and lab users are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the console's work home.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The work home.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ConsoleHome"
                },
                "example": {
                  "tenant": "coop-dl",
                  "generated_at": "2026-10-18T02:12:40Z",
                  "max_age_s": 10,
                  "day": {
                    "date": "2026-10-18",
                    "starts_at": "2026-10-17T17:00:00Z",
                    "time_zone": "Asia/Ho_Chi_Minh"
                  },
                  "scope": {
                    "all_facilities": false,
                    "facilities": [
                      {
                        "code": "VN-TGPH-021",
                        "name": "Tân Phú",
                        "lines": [
                          "A1",
                          "A2",
                          "B1"
                        ]
                      }
                    ]
                  },
                  "sections": {
                    "sessions": {
                      "state": "ok",
                      "total": 1,
                      "items": [
                        {
                          "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                          "lot": "LO-260928-014",
                          "variety": "Ri6",
                          "facility": "VN-TGPH-021",
                          "line": "A2",
                          "status": "open",
                          "opened_at": "2026-10-18T00:42:00Z",
                          "paused_at": null,
                          "fruits": 128,
                          "opened_by_you": true
                        }
                      ]
                    },
                    "work": {
                      "state": "ok",
                      "window": {
                        "per_facility": 1000,
                        "full": false
                      },
                      "tasks": {
                        "measure": {
                          "count": 1,
                          "oldest": [
                            {
                              "code": "LO-261018-002",
                              "facility": "VN-TGPH-021",
                              "since": "2026-10-18T01:05:00Z"
                            }
                          ]
                        },
                        "close": {
                          "count": 0,
                          "oldest": []
                        },
                        "sample": {
                          "count": 0,
                          "oldest": []
                        },
                        "lab_failed": {
                          "count": 0,
                          "oldest": []
                        },
                        "lab_waiting": {
                          "count": 1,
                          "oldest": [
                            {
                              "code": "LO-260927-009",
                              "facility": "VN-TGPH-021",
                              "since": "2026-10-17T09:30:00Z"
                            }
                          ]
                        },
                        "pack": {
                          "count": 1,
                          "oldest": [
                            {
                              "code": "LO-260927-011",
                              "facility": "VN-TGPH-021",
                              "since": "2026-10-17T10:20:00Z"
                            }
                          ]
                        },
                        "label": {
                          "count": 0,
                          "oldest": []
                        },
                        "ship": {
                          "count": 1,
                          "oldest": [
                            {
                              "code": "LO-260926-004",
                              "facility": "VN-TGPH-021",
                              "since": "2026-10-16T08:00:00Z"
                            }
                          ]
                        },
                        "recalled": {
                          "count": 0,
                          "oldest": []
                        }
                      }
                    },
                    "shipments": {
                      "state": "ok",
                      "open": 1,
                      "items": [
                        {
                          "code": "SH-260930-01",
                          "facility": "VN-TGPH-021",
                          "lots": 2,
                          "logger_check": "missing",
                          "created_at": "2026-10-17T08:00:00Z"
                        }
                      ],
                      "logger_missing": {
                        "count": 0,
                        "oldest": []
                      }
                    },
                    "review": {
                      "state": "ok",
                      "quarantined": 0,
                      "capped": false,
                      "oldest_received_at": null
                    },
                    "devices": {
                      "state": "ok",
                      "total": 1,
                      "capped": false,
                      "items": [
                        {
                          "device_id": "sf100-0417",
                          "name": "SF-100",
                          "facility": "VN-TGPH-021",
                          "measures": true,
                          "approval": "approved",
                          "ready": true,
                          "last_seen": "2026-10-18T02:11:58Z",
                          "calibration_valid_until": "2026-11-15T00:00:00Z"
                        }
                      ],
                      "gateways": [
                        {
                          "gateway_id": "gw-tp-01",
                          "name": "Station Tân Phú",
                          "facility": "VN-TGPH-021",
                          "last_heartbeat": "2026-10-18T02:11:00Z",
                          "silent": false
                        }
                      ],
                      "gateways_capped": false
                    },
                    "today": {
                      "state": "ok",
                      "lots_created": 2,
                      "lots_closed": 1,
                      "lots_packed": 0,
                      "shipments_departed": 0,
                      "messages": 5123,
                      "messages_capped": false
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, platform_admin and operator, through a signed-in session: an API token, an API client or the legacy token is refused; auditors and lab users are refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/lab/home": {
      "get": {
        "operationId": "getLabHome",
        "summary": "Read the lab portal's home",
        "description": "#286. For the caller's lab: whether it can sign (its status, accreditation, market approvals and keys) and its work, among its newest 500 samplings across every exporter: the samplings waiting for results, oldest first, with how many were drawn more than `target_hours` (48) ago; the reports stored without their PDF original; the reports stored in the last 7 days and how many failed. Never another lab's samplings. Computed at most every 30 seconds per lab: the server serves one answer for `max_age_s` seconds after `generated_at`. Read-only and not audited (a read). `no-store`. Allowed for a lab user through a signed-in session only (its lab only): an API token, an API client or the legacy token is refused (403), and so is every other role. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the lab portal's home.",
        "tags": [
          "labs"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The lab's home.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LabHome"
                },
                "example": {
                  "lab": {
                    "code": "LAB-VN-118",
                    "name": "Phòng kiểm nghiệm 118",
                    "status": "active",
                    "accreditation": "VILAS 118",
                    "valid_to": "2027-03-31",
                    "approvals": [
                      {
                        "market": "CN",
                        "status": "active",
                        "valid_to": "2027-12-31"
                      }
                    ],
                    "keys": {
                      "lab_held": 1,
                      "server_held": true
                    }
                  },
                  "generated_at": "2026-10-18T02:12:40Z",
                  "max_age_s": 30,
                  "window": {
                    "samplings": 500,
                    "full": false
                  },
                  "target_hours": 48,
                  "sections": {
                    "waiting": {
                      "state": "ok",
                      "count": 3,
                      "past_target": 1,
                      "items": [
                        {
                          "id": 71,
                          "lot": "LO-260927-009",
                          "exporter": "HTX Đắk Lắk",
                          "sample_count": 3,
                          "analytes": [
                            "cadmium",
                            "auramine_o"
                          ],
                          "selected_at": "2026-10-16T03:00:00Z"
                        }
                      ]
                    },
                    "pdf_missing": {
                      "state": "ok",
                      "count": 1,
                      "items": [
                        {
                          "id": 68,
                          "report_no": "KN-261015-0031",
                          "received_at": "2026-10-15T08:40:00Z"
                        }
                      ]
                    },
                    "sent": {
                      "state": "ok",
                      "count_7d": 4,
                      "failed_7d": 0,
                      "items": [
                        {
                          "id": 69,
                          "lot": "LO-260925-004",
                          "report_no": "KN-261016-0040",
                          "passed": true,
                          "received_at": "2026-10-16T07:10:00Z"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only a lab user of a lab, through a signed-in session), tenant not allowed (X-Tenant), two-factor required.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The caller's lab is not in the registry.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: lab",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/account/personal-data": {
      "get": {
        "operationId": "getMyPersonalData",
        "summary": "See the personal data held about me in this company",
        "description": "SELF-2-9 (#198). What the platform holds about the caller in the selected company (X-Tenant): name and email, role (and an operator's facilities), membership and account status, when they joined and accepted the staff privacy notice, whether two-step sign-in is on and the times of the most recent sign-ins. Never a secret. Allowed for only tenant_admin, operator and auditor, through a signed-in session: an API token, an API client or the legacy token is refused; a lab user and a platform admin acting for the company are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The member's personal data in this company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PersonalData"
                },
                "example": {
                  "user_id": 7,
                  "email": "op@coop.example",
                  "display_name": "Lan",
                  "company": {
                    "id": "coop-dl",
                    "name": "Coop DL"
                  },
                  "roles": [
                    "operator"
                  ],
                  "facilities": [
                    "VN-TGPH-021"
                  ],
                  "lab_id": null,
                  "membership_status": "active",
                  "account_status": "active",
                  "account_created_at": 1789000000.5,
                  "joined_at": 1789000000.5,
                  "notice_accepted_at": 1789000000.5,
                  "two_factor": true,
                  "recent_sign_ins": [
                    1790000000.5,
                    1789900000.5
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A bad `agronomist` (#351), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_agronomist": {
                    "value": {
                      "error": "bad agronomist: 0 or 1",
                      "code": "bad_agronomist"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "$ref": "#/components/responses/BadRequestId"
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, operator and auditor, through a signed-in session: an API token, an API client or the legacy token is refused; lab users and platform admins are refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The caller has no membership in the selected company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: membership",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "parameters": [
          {
            "name": "agronomist",
            "in": "query",
            "required": false,
            "x-not-in-sdk": true,
            "description": "#351: `1` adds `agronomist`, the caller's row of the platform's agronomist registry (null without one); `0` or none leaves it out and answers exactly as before; any other value is refused (400 `bad agronomist`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1"
          }
        ]
      }
    },
    "/v1/account/personal-data-requests": {
      "get": {
        "operationId": "listMyPersonalDataRequests",
        "summary": "List my requests about my personal data",
        "description": "SELF-2-9 (#198). The requests the caller sent in the selected company (X-Tenant), newest first, with their status. Allowed for only tenant_admin, operator and auditor, through a signed-in session: an API token, an API client or the legacy token is refused; a lab user and a platform admin acting for the company are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of requests.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PersonalDataRequestPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 4,
                      "kind": "correction",
                      "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
                      "status": "handled",
                      "created_at": 1790000000.5,
                      "handled_at": 1790003600.5
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, operator and auditor, through a signed-in session: an API token, an API client or the legacy token is refused; lab users and platform admins are refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createPersonalDataRequest",
        "summary": "Ask my company to show more of or correct my personal data",
        "description": "SELF-2-9 (#198). Sends the selected company's (X-Tenant) admins a request from the caller: `access` (show me more of the personal data you hold about me) or `correction` (correct it), with a plain-text message. The company is the controller of its members' data, so the request goes to its admins (the list on the Team screen), not to CropPath; there is no email. Stored as plain text exactly as typed (trimmed). At most 5 requests per person per day (across every company) and 50 per company per day (429). Audited (`personal_data_request.create`, in the same transaction; never the text). Allowed for only tenant_admin, operator and auditor, through a signed-in session: an API token, an API client or the legacy token is refused; a lab user and a platform admin acting for the company are refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PersonalDataRequestCreate"
              },
              "example": {
                "kind": "correction",
                "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A."
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The request, as the member sees it.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PersonalDataRequest"
                },
                "example": {
                  "id": 4,
                  "kind": "correction",
                  "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
                  "status": "open",
                  "created_at": 1790000000.5,
                  "handled_at": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a value outside the limits, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "kind": {
                    "value": {
                      "error": "invalid kind: one of access, correction",
                      "code": "invalid_kind"
                    }
                  },
                  "text": {
                    "value": {
                      "error": "invalid text: required, text of at most 2000 characters",
                      "code": "invalid_text"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown field: email",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, operator and auditor, through a signed-in session: an API token, an API client or the legacy token is refused; lab users and platform admins are refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only once the company has left CropPath; during its 30-day read-only window this stays open (owner decision A).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The caller has no active membership in the selected company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: membership",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "429": {
            "description": "Too many requests sent: at most 5 per person per day (code `too_many_personal_data_requests`) and 50 per company per day (code `too_many_personal_data_requests_company`, reached by the company's members together). Nothing was stored; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "person": {
                    "value": {
                      "error": "too many personal data requests: at most 5 per person per day",
                      "code": "too_many_personal_data_requests"
                    }
                  },
                  "company": {
                    "value": {
                      "error": "too many personal data requests (company): at most 50 per company per day",
                      "code": "too_many_personal_data_requests_company"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/personal-data-requests": {
      "get": {
        "operationId": "listCompanyPersonalDataRequests",
        "summary": "List the company's personal data requests",
        "description": "SELF-2-9 (#198). Every request the selected company's (X-Tenant) members sent about their personal data, newest first, with who sent it; `status` narrows the list. Allowed for only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only requests of this status.",
            "schema": {
              "type": "string",
              "enum": [
                "open",
                "handled"
              ]
            },
            "example": "open"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of requests.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyPersonalDataRequestPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 4,
                      "kind": "correction",
                      "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
                      "status": "handled",
                      "created_at": 1790000000.5,
                      "handled_at": 1790003600.5,
                      "user": {
                        "id": 7,
                        "email": "op@coop.example",
                        "display_name": "Lan"
                      },
                      "handled_by": "admin@coop.example"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `status`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "value": {
                      "error": "invalid status: one of open, handled",
                      "code": "invalid_status"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/personal-data-requests/{id}/handled": {
      "post": {
        "operationId": "markPersonalDataRequestHandled",
        "summary": "Mark a personal data request handled",
        "description": "SELF-2-9 (#198). A company admin marks a member's request handled once they have dealt with it; final. The member then sees the status and when it changed. Another company's request answers 404. Audited (`personal_data_request.handle`, in the same transaction; never the text). Allowed for only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The request id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "4"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The request, handled.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyPersonalDataRequest"
                },
                "example": {
                  "id": 4,
                  "kind": "correction",
                  "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
                  "status": "handled",
                  "created_at": 1790000000.5,
                  "handled_at": 1790003600.5,
                  "user": {
                    "id": 7,
                    "email": "op@coop.example",
                    "display_name": "Lan"
                  },
                  "handled_by": "admin@coop.example"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only once the company has left CropPath; during its 30-day read-only window this stays open (owner decision A).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No personal data request with this id in the selected company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 4",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The request was already handled; or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "handled": {
                    "value": {
                      "error": "already handled: this request was already marked handled",
                      "code": "already_handled"
                    }
                  },
                  "idempotency": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/company/offboarding": {
      "get": {
        "operationId": "getCompanyOffboarding",
        "summary": "Whether the company is leaving CropPath",
        "description": "SELF-2-4 (#193). The selected company's (X-Tenant) departure state: `active`, `leaving` (with the end of its read-only window, for the banner every member of the company sees; its admins' links to the full data export) or `left`. Allowed for the company's tenant_admin, operator and auditor members and platform_admin (acting for the company through X-Tenant) through a signed-in session only: an API token, an API client or the legacy token is refused (403); a lab user is refused (403).",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "responses": {
          "200": {
            "description": "The company's departure state.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyOffboarding"
                },
                "example": {
                  "status": "leaving",
                  "retention_years": 5,
                  "started_at": 1790000000.5,
                  "window_ends_at": 1792592000.5,
                  "left_at": null,
                  "retention_ends_at": 1949858000.5,
                  "steps_done": 0
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin, operator, auditor and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), or two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/tenants/{id}/offboarding": {
      "post": {
        "operationId": "startCompanyOffboarding",
        "summary": "Mark a company as leaving CropPath",
        "description": "SELF-2-4 (#193). Starts the company's departure: a 30-day read-only window in which its people still sign in, read and download the full data export (`POST /v1/company/exports`), while every other write of the company is refused (403 `company_read_only`) and its devices' messages are refused (`company_read_only`). After the window the background job stops sign-in for the company (members who belong to no other company are disabled; others lose this membership), revokes its API tokens, API clients and webhooks and removes its people's names and emails everywhere except the append-only activity log; one audit row per step, by `system:offboarding`. Sealed lot records, evidence and public lot pages stay for `retention_years` from each lot's seal; trust tiers never change. `retention_years` is required (owner decision D-S4: no default). Audited (`company.offboarding.start`, in the same transaction, in the company's own log). Allowed for platform_admin through a signed-in session only; the session must have confirmed its password within the last 10 minutes (SELF-1-2), else 401 `reauthentication_required` before anything is done.",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The company (tenant id).",
            "schema": {
              "type": "string"
            },
            "example": "coop-new"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CompanyOffboardingStart"
              },
              "example": {
                "retention_years": 5
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The company is leaving: its state.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyOffboarding"
                },
                "example": {
                  "status": "leaving",
                  "retention_years": 5,
                  "started_at": 1790000000.5,
                  "window_ends_at": 1792592000.5,
                  "left_at": null,
                  "retention_ends_at": 1949858000.5,
                  "steps_done": 0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a missing or out-of-range `retention_years` (a whole number from 1 to 30; there is no default), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: window_days",
                      "code": "unknown_fields"
                    }
                  },
                  "retention": {
                    "value": {
                      "error": "invalid retention_years: a whole number of years from 1 to 30",
                      "code": "invalid_retention_years"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: coop-new",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The company is already leaving or has left, or it is the company of CropPath's platform admins or the company record of CropPath's lab logins (`croppath-labs`, #283), which cannot leave.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "leaving": {
                    "value": {
                      "error": "already leaving: the company is already leaving CropPath",
                      "code": "already_leaving"
                    }
                  },
                  "left": {
                    "value": {
                      "error": "already left: the company has left CropPath",
                      "code": "already_left"
                    }
                  },
                  "platform": {
                    "value": {
                      "error": "platform company: the company of CropPath's platform admins cannot leave",
                      "code": "platform_company"
                    }
                  },
                  "lab_logins": {
                    "value": {
                      "error": "lab logins company: the company record of CropPath's lab logins cannot leave",
                      "code": "lab_logins_company"
                    }
                  }
                }
              }
            },
            "x-sdk-object": {
              "description": "The company is already leaving or has left, or it is the company of CropPath's platform admins, which cannot leave.",
              "headers": {
                "X-Request-Id": {
                  "$ref": "#/components/headers/X-Request-Id"
                }
              },
              "content": {
                "application/json": {
                  "schema": {
                    "$ref": "#/components/schemas/Error"
                  },
                  "examples": {
                    "leaving": {
                      "value": {
                        "error": "already leaving: the company is already leaving CropPath",
                        "code": "already_leaving"
                      }
                    },
                    "left": {
                      "value": {
                        "error": "already left: the company has left CropPath",
                        "code": "already_left"
                      }
                    },
                    "platform": {
                      "value": {
                        "error": "platform company: the company of CropPath's platform admins cannot leave",
                        "code": "platform_company"
                      }
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/tenants/{id}/offboarding/cancel": {
      "post": {
        "operationId": "cancelCompanyOffboarding",
        "summary": "Cancel a company's departure during its window",
        "description": "SELF-2-4 (#193). Cancels the departure of a company that is leaving, during its read-only window (or until the job has stopped its sign-in): the company works normally again. No body. Audited (`company.offboarding.cancel`, in the company's own log). Allowed for platform_admin through a signed-in session only, with a password confirmed within the last 10 minutes (SELF-1-2).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The company (tenant id).",
            "schema": {
              "type": "string"
            },
            "example": "coop-new"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The departure is cancelled: the company's state, `active`.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyOffboarding"
                },
                "example": {
                  "status": "active",
                  "retention_years": null,
                  "started_at": null,
                  "window_ends_at": null,
                  "left_at": null,
                  "retention_ends_at": null,
                  "steps_done": 0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, any field in the body, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: retention_years",
                      "code": "unknown_fields"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin only, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: coop-new",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The company is not leaving, or it has left (sign-in stopped; cancelling cannot restore it).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_leaving": {
                    "value": {
                      "error": "not leaving: the company is not leaving CropPath",
                      "code": "not_leaving"
                    }
                  },
                  "left": {
                    "value": {
                      "error": "already left: sign-in has stopped and the departure cannot be cancelled",
                      "code": "already_left"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/sandbox/accounts": {
      "post": {
        "operationId": "createSandboxAccount",
        "summary": "Create a sandbox account (hosted sandbox only)",
        "description": "The hosted sandbox only (#218, `x-sandbox-only`): on every other deployment, CropPath's live service included, this path answers 404 `no_such_route` for every method, exactly like an unknown path, and creates nothing.\n\nAnonymous: no session and no token. Creates a fresh company of its own (`tenant_id`, `sbx-` and 16 random characters) and returns, once, an API token for it (`api_token`, `agt_...`): role tenant_admin of that company only, valid 24 hours (`expires_at`, Unix seconds). Send it as `Authorization: Bearer` to `base_url` (the sandbox's address); it never reaches another company (404, like a missing record) or a platform operation (403). Within a few minutes the company holds the demo scenario: a packing house, a growing area and its grower, devices, a lot of 128 measured fruits with its lab results, packing, seal and shipment, as on the man1 and man2 mockups. The company and all its data are deleted 7 days after its creation (the sandbox's setting); no email is ever sent; webhooks refuse private and loopback addresses as everywhere.\n\nLimits: a client address creates at most 5 companies an hour (the sandbox's setting; the address is the `CF-Connecting-IP` a trusted proxy sends, else the socket peer), then 429 with `Retry-After` before anything is done; and the sandbox holds at most 500 live companies (its setting), then 503 `sandbox_full`. The body is empty or `{}`. Audited (`sandbox.account.create`, actor `system:sandbox`, in the creation's transaction: the company and the token's expiry, never the token). Every answer is `no-store`.",
        "tags": [
          "sandbox"
        ],
        "security": [],
        "x-sandbox-only": true,
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SandboxAccountCreate"
              },
              "example": {}
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new company and its API token, shown this once.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SandboxAccount"
                },
                "example": {
                  "tenant_id": "sbx-k3m7q2xw5zr4tn6p",
                  "api_token": "agt_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGx",
                  "expires_at": 1790086400.5,
                  "base_url": "https://sandbox-txng.theio.vn"
                }
              }
            }
          },
          "400": {
            "description": "A body that is not empty or `{}` (invalid JSON, not an object, or any field), or a bad X-Request-Id. Nothing is created.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "not_an_object": {
                    "value": {
                      "error": "expected a JSON object",
                      "code": "expected_a_json_object"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown fields: tenant_id",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Not the hosted sandbox: on every other deployment the path does not exist (`no_such_route`, for every method).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "no such route",
                  "code": "no_such_route"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many sandbox accounts from this client address (5 an hour unless the sandbox sets another limit). Nothing was done, and no audit row is written; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "The sandbox holds as many live companies as it may (500 unless it sets another cap): nothing is created; retry later. Companies are deleted 7 days after their creation, which frees places.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "sandbox full: the sandbox holds as many companies as it may; try again later",
                  "code": "sandbox_full"
                }
              }
            }
          }
        }
      }
    },
    "/v1/lots/{lot}/merge": {
      "post": {
        "operationId": "mergeLots",
        "summary": "Record a lot merge producing this lot",
        "description": "#91: records that the path's lot (the output) was produced by merging 2 to 50 other lots of the caller's tenant (the inputs), each with the kilograms taken from it: the `transform` event type of the event types vocabulary 1.2.0 (/developers/downloads/event-types-v1.json), FSMA 204's transformation CTE. The output must be a draft lot without cartons, produced by no earlier merge; each input closed, packed or shipped, of the output's product, never merged before and not on hold. Mass balance: output_kg may differ from the sum of the inputs' quantity_kg by at most 5 % of that sum, and a packed input gives at most its packed net mass plus 5 %. The merge happens at the output lot's facility and changes no lot's status. Trust (ADR 0001): the output's tier is at most the lowest displayed tier of its inputs (reason `limited_by_input`), so a merge never raises a tier. The merge is a TransformationEvent in the staff EPCIS document (GET /v1/lots/{lot}/epcis) and rows of the records export of each of its lots. Tenant-entered. Audited (`lot.merge`). Allowed for platform_admin and tenant_admin (the whole tenant) and for an operator signed in with a session (only within its facilities, for the output and every input); auditor and lab are refused. Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_write"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LotMergeRequest"
              },
              "example": {
                "inputs": [
                  {
                    "lot": "LO-260928-014",
                    "quantity_kg": 349.6
                  },
                  {
                    "lot": "LO-260929-002",
                    "quantity_kg": 120.4
                  }
                ],
                "output_kg": 468.5
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The merge as recorded.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotTransformation"
                },
                "example": {
                  "event_id": "6f1c2a9e-3b7d-4c55-9a51-0d2e8f4b7c13",
                  "lot": "LO-261002-031",
                  "facility": "VN-TGPH-021",
                  "inputs": [
                    {
                      "lot": "LO-260928-014",
                      "quantity_kg": 349.6
                    },
                    {
                      "lot": "LO-260929-002",
                      "quantity_kg": 120.4
                    }
                  ],
                  "input_kg": 470.0,
                  "output_kg": 468.5,
                  "mass_tolerance": 0.05,
                  "recorded_at": 1790090000.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a body that is not exactly inputs and output_kg, a bad input (not 2 to 50 distinct lot codes, the output lot itself, a quantity that is not a number of kilograms), a product mismatch, a mass balance violation (output_kg differs from the inputs' sum by more than 5 %, a quantity not above 0 or above 1 000 000 kg, or a packed input giving more than its packed net mass plus 5 %), or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: give inputs and output_kg",
                      "code": "invalid_body"
                    }
                  },
                  "invalid_inputs": {
                    "value": {
                      "error": "invalid inputs: 2 to 50 lots",
                      "code": "invalid_inputs"
                    }
                  },
                  "mass_balance": {
                    "value": {
                      "error": "mass balance: output_kg 600 differs from the inputs' 470 kg by more than 5%",
                      "code": "mass_balance"
                    }
                  },
                  "product_mismatch": {
                    "value": {
                      "error": "product mismatch: LO-260929-002 is not durian",
                      "code": "product_mismatch"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted, tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant, for the output lot or any input: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The output lot is not a draft lot without cartons, names a growing area or harvest of its own (`lot_has_own_origin`: a merged lot takes its origin from its inputs) or was already produced by a merge; or an input is not closed, packed or shipped, was already merged or is on hold (an open or escalated hold); or the merge would make the chain of merges deeper than a recall follows (`merge_chain_too_deep`: an input already 8 merges deep, or more than 64 merges behind the merged lot in all). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lot_is_open": {
                    "value": {
                      "error": "lot is open: a merge produces a new draft lot",
                      "code": "lot_is_open"
                    }
                  },
                  "lot_has_own_origin": {
                    "value": {
                      "error": "lot has own origin: LO-261002-031 names a growing area or harvest, and a merged lot takes its origin from its inputs",
                      "code": "lot_has_own_origin"
                    }
                  },
                  "lot_already_merged": {
                    "value": {
                      "error": "lot already merged: LO-260928-014",
                      "code": "lot_already_merged"
                    }
                  },
                  "lot_not_mergeable": {
                    "value": {
                      "error": "lot not mergeable: LO-260929-002 is open",
                      "code": "lot_not_mergeable"
                    }
                  },
                  "lot_on_hold": {
                    "value": {
                      "error": "lot on hold: LO-260929-002",
                      "code": "lot_on_hold"
                    }
                  },
                  "merge_chain_too_deep": {
                    "value": {
                      "error": "merge chain too deep: LO-260929-002 is 8 merges deep, at most 8",
                      "code": "merge_chain_too_deep"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/lots/{lot}/transformations": {
      "get": {
        "operationId": "getLotTransformations",
        "summary": "The lot merges a lot took part in",
        "description": "#91: the merge that produced the lot and the merge that consumed it, each null when none did. Allowed for every role that reads lots (an operator only within its facilities). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "lots"
        ],
        "security": [
          {
            "cookie": []
          },
          {
            "bearer": []
          },
          {
            "oauth2": [
              "lot_read"
            ]
          }
        ],
        "parameters": [
          {
            "name": "lot",
            "in": "path",
            "required": true,
            "description": "Lot code (unique within the tenant).",
            "schema": {
              "type": "string"
            },
            "example": "LO-260928-014"
          }
        ],
        "responses": {
          "200": {
            "description": "The lot's merges.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LotTransformations"
                },
                "example": {
                  "produced_by": {
                    "event_id": "6f1c2a9e-3b7d-4c55-9a51-0d2e8f4b7c13",
                    "lot": "LO-261002-031",
                    "facility": "VN-TGPH-021",
                    "inputs": [
                      {
                        "lot": "LO-260928-014",
                        "quantity_kg": 349.6
                      },
                      {
                        "lot": "LO-260929-002",
                        "quantity_kg": 120.4
                      }
                    ],
                    "input_kg": 470.0,
                    "output_kg": 468.5,
                    "mass_tolerance": 0.05,
                    "recorded_at": 1790090000.0
                  },
                  "consumed_by": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted or tenant not allowed (X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such lot for this tenant: a lot of another tenant, or of a facility outside an operator's facilities, answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: LO-260928-014",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-not-in-sdk": true
      }
    },
    "/v1/company/four-eyes": {
      "get": {
        "operationId": "getCompanyFourEyes",
        "summary": "Read the company's second admin approval setting",
        "description": "INTEGRITY-3 (#203). Whether the selected company's critical actions wait for a second admin, its active company admins and the requests waiting for a decision. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The setting.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FourEyesState"
                },
                "example": {
                  "require_second_admin": true,
                  "admins": 2,
                  "pending": 1,
                  "expires_after_s": 259200
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "updateCompanyFourEyes",
        "summary": "Require a second admin for critical actions, or stop",
        "description": "INTEGRITY-3 (#203). While `require_second_admin` is on, these actions of the company answer 403 `second_admin_approval_required` when called directly and change nothing: registering or rotating a device or gateway key (POST /v1/keys), approving a harvest app's key (POST /v1/harvest-keys/{kid}/approve), creating or rotating a facility's issuer key (POST /v1/facilities/{code}/issuer-keys), changing grading rules (PUT /v1/grading-rules/{variety}) and changing who must use two-step sign-in (PUT /v1/company/security). An admin asks for one with POST /v1/approval-requests and another admin approves it. Turning it on takes effect at once; turning it off while it is on is itself such an action (403 `second_admin_approval_required`: ask for `{\"require_second_admin\": false}` instead). Needs a password confirmed within the last 10 minutes. Audited (`company.four_eyes.update`, in the same transaction). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FourEyesUpdate"
              },
              "example": {
                "require_second_admin": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The setting, as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FourEyesState"
                },
                "example": {
                  "require_second_admin": true,
                  "admins": 2,
                  "pending": 1,
                  "expires_after_s": 259200
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, or `require_second_admin` missing or not true or false; or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: required",
                      "code": "unknown_fields"
                    }
                  },
                  "type": {
                    "value": {
                      "error": "require_second_admin must be true or false",
                      "code": "require_second_admin_must_be_true_or_false"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left. Also second admin approval required: turning it off while it is on.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  },
                  "second_admin_approval_required": {
                    "value": {
                      "error": "second admin approval required: ask for this action with POST /v1/approval-requests, and another admin of the company approves it",
                      "code": "second_admin_approval_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such company: a platform admin named one (X-Tenant) that does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/approval-requests": {
      "get": {
        "operationId": "listApprovalRequests",
        "summary": "List the company's second admin approval requests",
        "description": "INTEGRITY-3 (#203). The selected company's approval requests, newest first, one page: those waiting for a decision (`status=pending`, the default) or every request (`status=all`, an undecided one past its time shown `expired`). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "`pending` (default) or `all`.",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "all"
              ]
            },
            "example": "pending"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 100 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjE3fQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of requests.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApprovalRequestPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 17,
                      "action": "key.create",
                      "method": "POST",
                      "path": "/v1/keys",
                      "body": {
                        "kid": "gw-01-k2",
                        "owner_type": "gateway",
                        "owner_id": "gw-01",
                        "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
                      },
                      "status": "pending",
                      "requested_by": "admin@coop.example",
                      "requested_by_user_id": 12,
                      "requested_at": 1797000000.5,
                      "expires_at": 1797259200.5,
                      "decided_by": null,
                      "decided_as": null,
                      "decided_at": null,
                      "reason": null
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `status`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "value": {
                      "error": "status must be pending or all",
                      "code": "status_must_be_pending_or_all"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createApprovalRequest",
        "summary": "Ask a second admin to approve a critical action",
        "description": "INTEGRITY-3 (#203). Ask for one critical action (see PUT /v1/company/four-eyes): the method, path and JSON body the action takes when called directly. Nothing runs until another admin of the company approves it (POST /v1/approval-requests/{id}/approve) within 72 hours. The caller must hold the action's own role. At most 20 requests of a company wait at a time. Needs a password confirmed within the last 10 minutes. Audited (`approval_request.create`: the action and the expiry, never the body). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApprovalRequestCreate"
              },
              "example": {
                "method": "POST",
                "path": "/v1/keys",
                "body": {
                  "kid": "gw-01-k2",
                  "owner_type": "gateway",
                  "owner_id": "gw-01",
                  "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The request, pending.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApprovalRequest"
                },
                "example": {
                  "id": 17,
                  "action": "key.create",
                  "method": "POST",
                  "path": "/v1/keys",
                  "body": {
                    "kid": "gw-01-k2",
                    "owner_type": "gateway",
                    "owner_id": "gw-01",
                    "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
                  },
                  "status": "pending",
                  "requested_by": "admin@coop.example",
                  "requested_by_user_id": 12,
                  "requested_at": 1797000000.5,
                  "expires_at": 1797259200.5,
                  "decided_by": null,
                  "decided_as": null,
                  "decided_at": null,
                  "reason": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a method and path that are not a critical action, a body that is not a JSON object (or, for PUT /v1/company/four-eyes, anything but turning it off); or a bad X-Request-Id or Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: query",
                      "code": "unknown_fields"
                    }
                  },
                  "invalid_action": {
                    "value": {
                      "error": "invalid action: method and path of a critical action",
                      "code": "invalid_action"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: the action's JSON object",
                      "code": "invalid_body"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left. Also role not permitted when the caller does not hold the action's own role.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The company does not require a second admin (call the action directly), or 20 requests already wait for a decision. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "second_admin_approval_not_required": {
                    "value": {
                      "error": "second admin approval not required: the company has it turned off, call the action directly",
                      "code": "second_admin_approval_not_required"
                    }
                  },
                  "too_many_approval_requests": {
                    "value": {
                      "error": "too many approval requests: at most 20 wait for a decision at a time",
                      "code": "too_many_approval_requests"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/approval-requests/{id}/approve": {
      "post": {
        "operationId": "approveApprovalRequest",
        "summary": "Approve another admin's request: the action runs",
        "description": "INTEGRITY-3 (#203). Another admin of the company (or CropPath support, a platform admin acting for it: `decided_as` `platform_support`) approves a pending request. Its action runs now, exactly as if this admin had called it directly (with this admin's own role and facilities), in the action's own transaction together with the action's audit row and this approval's (`approval_request.approve`): all or nothing, and once only (a request decided meanwhile is 409 and the action is rolled back). The answer is the request and the action's own answer; an action that fails answers its own error and the request stays pending. The admin who asked cannot approve (403 `same_admin`). CropPath support approves only for a company with one admin (403 `company_has_second_admin`). Needs a password confirmed within the last 10 minutes and, for an account with two-step sign-in, a code confirmed within the last 5 (step-up, #87). An approval never raises a trust tier by itself. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The approval request id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "17"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Approved: the request and the action's answer.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApprovalRequestApproved"
                },
                "example": {
                  "request": {
                    "id": 17,
                    "action": "key.create",
                    "method": "POST",
                    "path": "/v1/keys",
                    "body": {
                      "kid": "gw-01-k2",
                      "owner_type": "gateway",
                      "owner_id": "gw-01",
                      "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
                    },
                    "status": "approved",
                    "requested_by": "admin@coop.example",
                    "requested_by_user_id": 12,
                    "requested_at": 1797000000.5,
                    "expires_at": 1797259200.5,
                    "decided_by": "second@coop.example",
                    "decided_as": "company_admin",
                    "decided_at": 1797003600.5,
                    "reason": null
                  },
                  "result": {
                    "kid": "gw-01-k2",
                    "owner_type": "gateway"
                  }
                }
              }
            }
          },
          "400": {
            "description": "A body with any field, invalid JSON, a bad X-Request-Id or Idempotency-Key header; or the action's own 400.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: an approval takes no input",
                      "code": "unknown_field"
                    }
                  },
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session that must confirm its password (`reauthentication_required`) or, with two-step sign-in, its password and a code (`mfa_step_up_required`) with POST /v1/auth/reauth, then repeat the request; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left. Also same admin: the admin who asked cannot decide their own request. Also company has second admin: CropPath support (a platform admin acting for the company) decides only for a company with one active company admin.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  },
                  "same_admin": {
                    "value": {
                      "error": "same admin: another admin of the company must decide this request",
                      "code": "same_admin"
                    }
                  },
                  "company_has_second_admin": {
                    "value": {
                      "error": "company has second admin: CropPath support decides only for a company with one admin, another admin of the company must decide this request",
                      "code": "company_has_second_admin"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No approval request of this company has this id (another company's answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 17",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The request was already approved or rejected, or it expired (72 hours); or the action's own 409. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "approval_request_not_pending": {
                    "value": {
                      "error": "approval request not pending: it was already approved or rejected",
                      "code": "approval_request_not_pending"
                    }
                  },
                  "approval_request_expired": {
                    "value": {
                      "error": "approval request expired: ask for the action again",
                      "code": "approval_request_expired"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "The approved action's own 503: an issuer key cannot be created because no key-encryption key is configured (AGRITRACE_ISSUER_KEK) or the store cannot be used; nothing changed and the request stays pending. Retry after `Retry-After` seconds once it is configured.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "issuer keys unavailable: AGRITRACE_ISSUER_KEK is not configured",
                  "code": "issuer_keys_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/approval-requests/{id}/reject": {
      "post": {
        "operationId": "rejectApprovalRequest",
        "summary": "Reject another admin's request",
        "description": "INTEGRITY-3 (#203). Another admin of the company (or CropPath support) rejects a pending request, with an optional reason kept on the request: nothing runs. The admin who asked cannot reject (403 `same_admin`). CropPath support rejects only for a company with one admin (403 `company_has_second_admin`). Needs a password confirmed within the last 10 minutes and, for an account with two-step sign-in, a code confirmed within the last 5 (step-up, #87). Audited (`approval_request.reject`: the action and who asked, never the reason). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The approval request id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "17"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApprovalRequestRejection"
              },
              "example": {
                "reason": "Not our gateway."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Rejected.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Idempotent-Replayed": {
                "$ref": "#/components/headers/Idempotent-Replayed"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApprovalRequest"
                },
                "example": {
                  "id": 17,
                  "action": "key.create",
                  "method": "POST",
                  "path": "/v1/keys",
                  "body": {
                    "kid": "gw-01-k2",
                    "owner_type": "gateway",
                    "owner_id": "gw-01",
                    "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
                  },
                  "status": "rejected",
                  "requested_by": "admin@coop.example",
                  "requested_by_user_id": 12,
                  "requested_at": 1797000000.5,
                  "expires_at": 1797259200.5,
                  "decided_by": "second@coop.example",
                  "decided_as": "company_admin",
                  "decided_at": 1797003600.5,
                  "reason": "Not our gateway."
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, an empty or too long reason; or a bad X-Request-Id or Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: note",
                      "code": "unknown_fields"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: a string of 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session that must confirm its password (`reauthentication_required`) or, with two-step sign-in, its password and a code (`mfa_step_up_required`) with POST /v1/auth/reauth, then repeat the request; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left. Also same admin: the admin who asked cannot decide their own request. Also company has second admin: CropPath support (a platform admin acting for the company) decides only for a company with one active company admin.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  },
                  "same_admin": {
                    "value": {
                      "error": "same admin: another admin of the company must decide this request",
                      "code": "same_admin"
                    }
                  },
                  "company_has_second_admin": {
                    "value": {
                      "error": "company has second admin: CropPath support decides only for a company with one admin, another admin of the company must decide this request",
                      "code": "company_has_second_admin"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No approval request of this company has this id (another company's answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 17",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The request was already approved or rejected, or it expired (72 hours). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed (too large to store, or never recorded).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "approval_request_not_pending": {
                    "value": {
                      "error": "approval request not pending: it was already approved or rejected",
                      "code": "approval_request_not_pending"
                    }
                  },
                  "approval_request_expired": {
                    "value": {
                      "error": "approval request expired: ask for the action again",
                      "code": "approval_request_expired"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  },
                  "idempotency_key_unrecorded": {
                    "value": {
                      "error": "idempotency key used: the request ran but its response was not recorded",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/passkeys": {
      "get": {
        "operationId": "listMyPasskeys",
        "summary": "The signed-in user's passkeys",
        "description": "#87. Every passkey of the signed-in user, oldest first: its nickname, algorithm, transports, attestation format, when it was added and last used, and when a sign-in with it was refused because its signature counter did not move forward (a possibly copied authenticator). Never a credential id, a public key or a user handle. Session routes are open to every signed-in user, whatever the role, and act on that user's own passkeys only. `no-store`. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The passkeys.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PasskeyList"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "nickname": "Work phone",
                      "algorithm": "ES256",
                      "transports": [
                        "hybrid",
                        "internal"
                      ],
                      "attestation_format": "none",
                      "created_at": 1790060400,
                      "last_used_at": 1790086380,
                      "clone_warning_at": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant). Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "tenant not allowed",
                  "code": "tenant_not_allowed"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "registerPasskey",
        "summary": "Add a passkey to the signed-in user's account",
        "description": "#87. The answer of navigator.credentials.create() for the options of startPasskeyRegistration, verified as WebAuthn Level 2 section 7.1 asks: the client data is a `webauthn.create` for that single-use challenge (used up by this request whatever its outcome, valid 5 minutes) at the public origin, the authenticator data starts with the SHA-256 of the RP ID (the public origin's host) and has the user present and user verified flags, and the credential key is ES256, RS256 (2048 bits or more) or EdDSA. Attestation `none` is enough (`packed` self attestation is checked; another format is stored by name, never trusted). An account has at most 10 passkeys; a credential is registered once across all accounts (409). Audited (`auth.passkey.register`, in the same transaction: the passkey's id, algorithm and attestation format; never key material). A session must have confirmed its password within the last 10 minutes (SELF-1-2, #183), else 401 `reauthentication_required` before anything is done. Unsafe method: needs `X-CSRF-Token` and an allowed Origin. Session routes are open to every signed-in user, whatever the role, and act on that user's own passkeys only. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PasskeyRegistration"
              },
              "example": {
                "client_data_json": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIn0",
                "attestation_object": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YUA",
                "transports": [
                  "internal"
                ],
                "nickname": "Work phone"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The passkey was added.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Passkey"
                },
                "example": {
                  "id": 3,
                  "nickname": "Work phone",
                  "algorithm": "ES256",
                  "transports": [
                    "hybrid",
                    "internal"
                  ],
                  "attestation_format": "none",
                  "created_at": 1790060400,
                  "last_used_at": null,
                  "clone_warning_at": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a malformed nickname or transports, a bad X-Request-Id; or the passkey does not verify (`invalid_passkey`: its challenge is unknown, used, expired or another account's, or a check failed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "nickname": {
                    "value": {
                      "error": "nickname too long: at most 64 characters",
                      "code": "nickname_too_long"
                    }
                  },
                  "invalid_passkey": {
                    "value": {
                      "error": "invalid passkey: challenge unknown or used",
                      "code": "invalid_passkey"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "session": {
                    "value": {
                      "error": "not authenticated",
                      "code": "not_authenticated"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The account has 10 passkeys already, or this passkey is registered already.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "too_many": {
                    "value": {
                      "error": "too many passkeys: an account has at most 10",
                      "code": "too_many_passkeys"
                    }
                  },
                  "registered": {
                    "value": {
                      "error": "passkey already registered",
                      "code": "passkey_already_registered"
                    }
                  }
                }
              }
            }
          },
          "503": {
            "description": "The server has no public origin (AGRITRACE_PUBLIC_ORIGIN), the passkeys' Relying Party: passkeys cannot be used.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "passkeys unavailable: the server has no public origin (AGRITRACE_PUBLIC_ORIGIN)",
                  "code": "passkeys_unavailable"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/auth/passkeys/registration-options": {
      "post": {
        "operationId": "startPasskeyRegistration",
        "summary": "Options for adding a passkey",
        "description": "#87. The options for navigator.credentials.create(): a single-use challenge (32 random bytes, stored as their SHA-256 only, valid 5 minutes; a new one replaces the account's earlier one), the Relying Party (the public origin's host), the account's user handle (random, never the account id), ES256, EdDSA and RS256, attestation `none`, a discoverable credential with user verification required, and the account's passkeys to exclude. The body is empty or `{}`. Not audited (a challenge changes no record; the registration is audited). A session must have confirmed its password within the last 10 minutes, else 401 `reauthentication_required`. Unsafe method: needs `X-CSRF-Token` and an allowed Origin. Session routes are open to every signed-in user, whatever the role, and act on that user's own passkeys only. `no-store`. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The options.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PasskeyCreationOptions"
                },
                "example": {
                  "public_key": {
                    "challenge": "q83vEjRWeJCrze8SNFZ4kKvN7xI0VniQq83vEjRWeJA",
                    "rp": {
                      "id": "txng.theio.vn",
                      "name": "CropPath"
                    },
                    "user": {
                      "id": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGk",
                      "name": "alice@coop.example",
                      "displayName": "Alice"
                    },
                    "pubKeyCredParams": [
                      {
                        "type": "public-key",
                        "alg": -7
                      },
                      {
                        "type": "public-key",
                        "alg": -8
                      },
                      {
                        "type": "public-key",
                        "alg": -257
                      }
                    ],
                    "timeout": 300000,
                    "attestation": "none",
                    "authenticatorSelection": {
                      "residentKey": "required",
                      "requireResidentKey": true,
                      "userVerification": "required"
                    },
                    "excludeCredentials": [
                      {
                        "type": "public-key",
                        "id": "AAECAwQFBgcICQoLDA0ODw",
                        "transports": [
                          "internal"
                        ]
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a field (the body takes none) or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`: confirm it with POST /v1/auth/reauth, then repeat the request; nothing was done).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "session": {
                    "value": {
                      "error": "not authenticated",
                      "code": "not_authenticated"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The account has 10 passkeys already.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many passkeys: an account has at most 10",
                  "code": "too_many_passkeys"
                }
              }
            }
          },
          "503": {
            "description": "The server has no public origin (AGRITRACE_PUBLIC_ORIGIN), the passkeys' Relying Party: passkeys cannot be used.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "passkeys unavailable: the server has no public origin (AGRITRACE_PUBLIC_ORIGIN)",
                  "code": "passkeys_unavailable"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/auth/passkeys/{id}": {
      "patch": {
        "operationId": "renamePasskey",
        "summary": "Rename one of the signed-in user's passkeys",
        "description": "#87. Sets the passkey's nickname (at most 64 characters, spaces trimmed, no control character; empty to clear it). Another user's passkey answers 404 like a missing one. Audited (`auth.passkey.rename`, in the same transaction; never the nickname). Unsafe method: needs `X-CSRF-Token` and an allowed Origin. Session routes are open to every signed-in user, whatever the role, and act on that user's own passkeys only. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The passkey's id (from listMyPasskeys).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PasskeyRename"
              },
              "example": {
                "nickname": "Work phone"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Renamed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Passkey"
                },
                "example": {
                  "id": 3,
                  "nickname": "Work phone",
                  "algorithm": "ES256",
                  "transports": [
                    "hybrid",
                    "internal"
                  ],
                  "attestation_format": "none",
                  "created_at": 1790060400,
                  "last_used_at": 1790086380,
                  "clone_warning_at": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, no or a malformed nickname, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "required": {
                    "value": {
                      "error": "nickname is required",
                      "code": "nickname_is_required"
                    }
                  },
                  "too_long": {
                    "value": {
                      "error": "nickname too long: at most 64 characters",
                      "code": "nickname_too_long"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session cookie.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not authenticated",
                  "code": "not_authenticated"
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No passkey of the signed-in user with that id (another user's passkey answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      },
      "delete": {
        "operationId": "removePasskey",
        "summary": "Remove one of the signed-in user's passkeys",
        "description": "#87. Deletes the passkey: it cannot sign in from then on (sessions it opened stay open; end them with revokeMySession). Another user's passkey answers 404 like a missing one. Audited (`auth.passkey.remove`, in the same transaction). Step-up: a session must have confirmed its password within the last 10 minutes (`reauthentication_required`) and, for an account with two-step sign-in, a code (or a passkey sign-in) within the last 5 minutes (`mfa_step_up_required`, #87 part A), else 401 before anything is done (no audit row). Unsafe method: needs `X-CSRF-Token` and an allowed Origin. Session routes are open to every signed-in user, whatever the role, and act on that user's own passkeys only. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The passkey's id (from listMyPasskeys).",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "3"
          }
        ],
        "responses": {
          "204": {
            "description": "Removed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session cookie; or a session whose password was last confirmed more than 10 minutes ago (`reauthentication_required`); or, for an account with two-step sign-in, a session whose code (or passkey sign-in) was last confirmed more than 5 minutes ago (`mfa_step_up_required`): confirm with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "session": {
                    "value": {
                      "error": "not authenticated",
                      "code": "not_authenticated"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is refused: tenant not allowed (X-Tenant), CSRF token missing or invalid, origin not allowed. Session routes are open to every role, so there is no role check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No passkey of the signed-in user with that id (another user's passkey answers the same).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/auth/passkeys/authentication-options": {
      "post": {
        "operationId": "startPasskeySignIn",
        "summary": "Options for signing in with a passkey",
        "description": "#87. Anonymous, like login: the options for navigator.credentials.get(), with a single-use challenge (stored as its SHA-256 only, valid 5 minutes), the RP ID and user verification required; no allowed credentials, so the authenticator offers the person's passkeys for this site (no email first). The body is empty or `{}`. Not audited (a challenge changes no record; the sign-in is audited). Takes a token from the login rate-limit bucket before anything else. When an Origin header is sent it must be allowed. `no-store`. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The options.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PasskeyRequestOptions"
                },
                "example": {
                  "public_key": {
                    "challenge": "q83vEjRWeJCrze8SNFZ4kKvN7xI0VniQq83vEjRWeJA",
                    "rpId": "txng.theio.vn",
                    "timeout": 300000,
                    "userVerification": "required",
                    "allowCredentials": []
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a field (the body takes none) or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "429": {
            "description": "Too many sign-in attempts from this client address (the login bucket). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "503": {
            "description": "The server has no public origin (AGRITRACE_PUBLIC_ORIGIN), the passkeys' Relying Party: passkeys cannot be used.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "passkeys unavailable: the server has no public origin (AGRITRACE_PUBLIC_ORIGIN)",
                  "code": "passkeys_unavailable"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/auth/passkeys/login": {
      "post": {
        "operationId": "signInWithPasskey",
        "summary": "Sign in with a passkey",
        "description": "#87. Anonymous, like login: the answer of navigator.credentials.get() for the options of startPasskeySignIn opens a session (cookie, `csrf_token`), in one transaction with the audit row (`auth.login`, `second_factor: passkey`; a refusal is `auth.login.passkey.failed`, naming the account only when the passkey's signature verified). Verified as WebAuthn Level 2 section 7.2 asks: the single-use challenge (used up whatever the outcome), the `webauthn.get` client data at the public origin, the RP ID hash, the user present and user verified flags, the user handle and the signature with the stored key. A signature counter that does not move forward (unless the authenticator keeps none) is refused and marks the passkey (`clone_warning_at`). A disabled account is refused. User verification stands in for the password and the passkey is the second factor: the session counts as having proved both now, so it satisfies two-step sign-in (SELF-1-6, #187) and the step-up of the highest-impact writes (#87 part A) for as long as a code would. Every refusal is the same 401. Takes a token from the login rate-limit bucket before anything else. When an Origin header is sent it must be allowed. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PasskeyLogin"
              },
              "example": {
                "credential_id": "AAECAwQFBgcICQoLDA0ODw",
                "client_data_json": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0",
                "authenticator_data": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAAAQ",
                "signature": "MEUCIQDf8bWWy-8Y5H0SsX0vT6g",
                "user_handle": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGk"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Signed in. Send `csrf_token` as `X-CSRF-Token` on unsafe methods.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuthSession"
                },
                "example": {
                  "user": {
                    "id": 1,
                    "email": "alice@coop.example",
                    "display_name": "Alice"
                  },
                  "memberships": [
                    {
                      "tenant": "coop-dl",
                      "role": "tenant_admin",
                      "facilities": null,
                      "lab_id": null
                    }
                  ],
                  "csrf_token": "q3Vb0mXl2sQ"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a field missing or not text, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "required": {
                    "value": {
                      "error": "credential_id, client_data_json, authenticator_data, signature and user_handle are required",
                      "code": "credential_id_client_data_json_authenticator_data_signature_and_user_handle_are_required"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "The passkey did not verify, is unknown, its challenge is unknown, used or expired, its counter did not move forward, or the account is disabled.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "invalid passkey",
                  "code": "invalid_passkey"
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "429": {
            "description": "Too many sign-in attempts from this client address (the login bucket). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "503": {
            "description": "The server has no public origin (AGRITRACE_PUBLIC_ORIGIN), the passkeys' Relying Party: passkeys cannot be used.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "passkeys unavailable: the server has no public origin (AGRITRACE_PUBLIC_ORIGIN)",
                  "code": "passkeys_unavailable"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/growers/{id}/consents": {
      "get": {
        "operationId": "listGrowerConsents",
        "summary": "A grower's consents",
        "description": "#163. The grower's consents in force (`in_force`) and its consent records, newest first: every decision the grower made about showing their name or orchard position (per market or for every market), how it was captured, its evidence's SHA-256 and who recorded it. Another company's grower answers 404. Allowed for only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients yet (`x-not-in-sdk`).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Grower id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "The consents in force and one page of records.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowerConsentPage"
                },
                "example": {
                  "grower_id": 12,
                  "in_force": [],
                  "items": [
                    {
                      "id": 32,
                      "grower_id": 12,
                      "purpose": "public_name",
                      "market": null,
                      "decision": "withdrawn",
                      "channel": "in_person",
                      "evidence_sha256": null,
                      "consent_date": null,
                      "scope": null,
                      "request_id": null,
                      "recorded_at": 1790086400.5,
                      "recorded_by": "user-7"
                    },
                    {
                      "id": 31,
                      "grower_id": 12,
                      "purpose": "public_name",
                      "market": null,
                      "decision": "granted",
                      "channel": "paper",
                      "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                      "consent_date": "2026-09-12",
                      "scope": "Fruit pages, every market",
                      "request_id": null,
                      "recorded_at": 1790000000.5,
                      "recorded_by": "user-7"
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such grower in the selected company (a grower of another company, or an id that is not a positive integer, answers exactly like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "recordGrowerConsent",
        "summary": "Record a grower's consent decision",
        "description": "#163. Appends a grower's decision (`granted` or `withdrawn`) about one purpose and market. A grant needs written evidence (`paper` or `electronic`, with the evidence's SHA-256); a withdrawal is accepted however the grower made it. The public name for every market is also the grower's `public_consent` (with `consent_date` and `consent_scope`), which the public fruit page reads: a withdrawal takes the name off it at once (a cached copy at the edge lasts up to 60 seconds). The public fruit page names the grower with the `public_name` consent for the destination market of the shipment its lot is on (the more specific decision wins: a withdrawal for that market hides the name there even while the every-market consent stands), or else with the one for every market; a lot on no shipment has no market, so a consent for one market never names the grower there. While the company is leaving CropPath (the read-only window) a withdrawal is still accepted and a grant is refused 403 `company_read_only`; once the company has left, a platform admin acting for it can still record a withdrawal (the public pages stay up for the retention period). 409 when the decision does not change what is in force. Audited (`grower.consent.record`, in the same transaction: the purpose, market, decision and channel; never the evidence hash or the scope). Allowed for only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients yet (`x-not-in-sdk`).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Grower id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowerConsentCreate"
              },
              "example": {
                "purpose": "public_name",
                "market": null,
                "decision": "granted",
                "channel": "paper",
                "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                "consent_date": "2026-09-12",
                "scope": "Fruit pages, every market"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The new consent record.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowerConsent"
                },
                "example": {
                  "id": 31,
                  "grower_id": 12,
                  "purpose": "public_name",
                  "market": null,
                  "decision": "granted",
                  "channel": "paper",
                  "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                  "consent_date": "2026-09-12",
                  "scope": "Fruit pages, every market",
                  "request_id": null,
                  "recorded_at": 1790000000.5,
                  "recorded_by": "user-7"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a value outside the limits (a grant without written evidence included), or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "channel": {
                    "value": {
                      "error": "invalid channel: a grant needs written evidence (paper, electronic)",
                      "code": "invalid_channel"
                    }
                  },
                  "evidence": {
                    "value": {
                      "error": "invalid evidence_sha256: a grant needs the SHA-256 of its evidence",
                      "code": "invalid_evidence_sha256"
                    }
                  },
                  "market": {
                    "value": {
                      "error": "invalid market: two capital letters (ISO 3166-1 alpha-2), or null for every market",
                      "code": "invalid_market"
                    }
                  },
                  "unknown": {
                    "value": {
                      "error": "unknown field: name",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such grower in the selected company (a grower of another company, or an id that is not a positive integer, answers exactly like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The decision does not change what is in force (a grant of a consent in force, a withdrawal of one that is not); or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "already_granted": {
                    "value": {
                      "error": "already granted: this consent is already in force",
                      "code": "already_granted"
                    }
                  },
                  "not_granted": {
                    "value": {
                      "error": "not granted: this consent is not in force, there is nothing to withdraw",
                      "code": "not_granted"
                    }
                  },
                  "idempotency": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/grower-data-requests": {
      "get": {
        "operationId": "listGrowerDataRequests",
        "summary": "List the growers' data requests",
        "description": "#163. The requests the company's growers made about their personal data (access, rectification, erasure, objection), newest first, with the day each answer is due and whether it is overdue; `status` and `grower_id` narrow the list. Allowed for only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients yet (`x-not-in-sdk`).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only requests of this status.",
            "schema": {
              "type": "string",
              "enum": [
                "open",
                "handled"
              ]
            },
            "example": "open"
          },
          {
            "name": "grower_id",
            "in": "query",
            "required": false,
            "description": "Only this grower's requests.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "12"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "1 to 200 (default 50).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJiZWZvcmUiOjEyfQ"
          }
        ],
        "responses": {
          "200": {
            "description": "One page of requests.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowerDataRequestPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 4,
                      "grower": {
                        "id": 12,
                        "name": "Nguyễn Văn An"
                      },
                      "kind": "erasure",
                      "channel": "paper",
                      "text": "Please take my name off the fruit pages.",
                      "received_on": "2026-09-28",
                      "due_on": "2026-10-28",
                      "overdue": false,
                      "status": "handled",
                      "created_at": 1790000000.5,
                      "created_by": "user-7",
                      "handled_at": 1790086400.5,
                      "handled_by": "user-7",
                      "answer": "Your name no longer shows on the public fruit pages. The signed lot records never named you; the company keeps your name in its own registry for traceability.",
                      "withdrawn": [
                        {
                          "purpose": "public_name",
                          "market": null
                        }
                      ]
                    }
                  ],
                  "next_cursor": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `status`, `grower_id`, `limit` or `cursor`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "value": {
                      "error": "invalid status: one of open, handled",
                      "code": "invalid_status"
                    }
                  },
                  "grower_id": {
                    "value": {
                      "error": "invalid grower_id: a grower id",
                      "code": "invalid_grower_id"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createGrowerDataRequest",
        "summary": "Record a grower's data request",
        "description": "#163. Records a request a grower made to the company about their personal data, as received: `access`, `rectification`, `erasure` or `objection`, the channel, the day received and the grower's words (plain text). The answer is due 30 days after the day received (`due_on`, a proposal pending counsel). Open while the company is leaving CropPath (the read-only window), like a member's personal data request; refused 403 `company_read_only` once it has left. Audited (`grower_data_request.create`, in the same transaction: the kind, the grower and the channel; never the text). Allowed for only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients yet (`x-not-in-sdk`).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowerDataRequestCreate"
              },
              "example": {
                "grower_id": 12,
                "kind": "erasure",
                "channel": "paper",
                "received_on": "2026-09-28",
                "text": "Please take my name off the fruit pages."
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The request.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowerDataRequest"
                },
                "example": {
                  "id": 4,
                  "grower": {
                    "id": 12,
                    "name": "Nguyễn Văn An"
                  },
                  "kind": "erasure",
                  "channel": "paper",
                  "text": "Please take my name off the fruit pages.",
                  "received_on": "2026-09-28",
                  "due_on": "2026-10-28",
                  "overdue": false,
                  "status": "open",
                  "created_at": 1790000000.5,
                  "created_by": "user-7",
                  "handled_at": null,
                  "handled_by": null,
                  "answer": null,
                  "withdrawn": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a value outside the limits, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "kind": {
                    "value": {
                      "error": "invalid kind: one of access, rectification, erasure, objection",
                      "code": "invalid_kind"
                    }
                  },
                  "received_on": {
                    "value": {
                      "error": "invalid received_on: a date YYYY-MM-DD from 2000-01-01, not after today",
                      "code": "invalid_received_on"
                    }
                  },
                  "text": {
                    "value": {
                      "error": "invalid text: required, text of at most 2000 characters",
                      "code": "invalid_text"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such grower in the selected company (another company's answers exactly like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "idempotency": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/grower-data-requests/{id}/handled": {
      "post": {
        "operationId": "handleGrowerDataRequest",
        "summary": "Mark a grower's data request handled",
        "description": "#163. Marks the request handled with the answer given to the grower (final). For an erasure or an objection, `withdraw_public` also withdraws every consent in force of the grower (each recorded as a `data_request` withdrawal naming the request), so the name leaves the public fruit page at once; `withdrawn` lists them. The answer can say that signed lot records never name a grower, so nothing signed is changed. Another company's request answers 404. Open while the company is leaving CropPath (the read-only window), like a member's personal data request; refused 403 `company_read_only` once it has left. Audited (`grower_data_request.handle`, in the same transaction: the kind, the grower and what was withdrawn; never the answer). Allowed for only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients yet (`x-not-in-sdk`).",
        "tags": [
          "registry"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The request id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "4"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GrowerDataRequestHandle"
              },
              "example": {
                "answer": "Your name no longer shows on the public fruit pages. The signed lot records never named you; the company keeps your name in its own registry for traceability.",
                "withdraw_public": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The request, handled.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GrowerDataRequest"
                },
                "example": {
                  "id": 4,
                  "grower": {
                    "id": 12,
                    "name": "Nguyễn Văn An"
                  },
                  "kind": "erasure",
                  "channel": "paper",
                  "text": "Please take my name off the fruit pages.",
                  "received_on": "2026-09-28",
                  "due_on": "2026-10-28",
                  "overdue": false,
                  "status": "handled",
                  "created_at": 1790000000.5,
                  "created_by": "user-7",
                  "handled_at": 1790086400.5,
                  "handled_by": "user-7",
                  "answer": "Your name no longer shows on the public fruit pages. The signed lot records never named you; the company keeps your name in its own registry for traceability.",
                  "withdrawn": [
                    {
                      "purpose": "public_name",
                      "market": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, an answer outside the limits, `withdraw_public` for a request that is not an erasure or an objection, or a bad X-Request-Id; or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "answer": {
                    "value": {
                      "error": "invalid answer: required, text of at most 2000 characters",
                      "code": "invalid_answer"
                    }
                  },
                  "withdraw_public": {
                    "value": {
                      "error": "invalid withdraw_public: only for an erasure or an objection",
                      "code": "invalid_withdraw_public"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin (acting for the company through X-Tenant), through a signed-in session: an API token, an API client or the legacy token is refused); tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods). SELF-2-4 (#193): also company read-only while the company is leaving CropPath or has left (its records can be read and exported, not changed).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No grower data request with this id in the selected company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 4",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The request was already handled; or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "handled": {
                    "value": {
                      "error": "already handled: this request was already marked handled",
                      "code": "already_handled"
                    }
                  },
                  "idempotency": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/auth/oidc/start": {
      "post": {
        "operationId": "startOidcSignIn",
        "summary": "Begin a sign-in with the company's identity provider",
        "description": "#87 (OpenID Connect). Anonymous, like login: for a company whose admins set up an identity provider (PUT /v1/company/identity-provider), the provider's authorization URL to send the browser to (the authorization code flow with PKCE S256 and the company's own redirect URI, `{origin}/login/oidc/{company}`), and an HttpOnly cookie (`__Host-agt_oidc`) that holds the sign-in for 10 minutes and binds it to this browser: the state's SHA-256, the nonce and the code verifier, encrypted (AES-256-GCM under a key derived from AGRITRACE_ISSUER_KEK). Nothing is stored on the server, so starts never fill up. A company without an enabled provider and an unknown company answer the same 404. Not audited (it changes no account or record; finishing the sign-in is). Takes a token from the login rate-limit bucket before anything else. When an Origin header is sent it must be allowed. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OidcStart"
              },
              "example": {
                "company": "coop-dl"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Send the browser to `authorization_url`.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OidcStarted"
                },
                "example": {
                  "authorization_url": "https://login.coop.example/authorize?response_type=code&client_id=croppath-console&redirect_uri=https%3A%2F%2Ftxng.theio.vn%2Flogin%2Foidc%2Fcoop-dl&scope=openid+email&state=q3Vb0mXl2sQ&nonce=Zx9a&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256",
                  "expires_at": 1790087000.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, `company` missing or not text, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "required": {
                    "value": {
                      "error": "company is required",
                      "code": "company_is_required"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "404": {
            "description": "The company has no enabled identity provider, or there is no such company.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: identity provider",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many sign-in attempts from this client address (the login bucket). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "502": {
            "description": "The company's identity provider did not answer, or answered outside the rules (its discovery document or key set could not be read). Nothing was stored; try again later.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "identity provider unreachable",
                  "code": "identity_provider_unreachable"
                }
              }
            }
          },
          "503": {
            "description": "This deployment does not allow sign-in with an identity provider (no AGRITRACE_PUBLIC_ORIGIN or no AGRITRACE_OIDC_ALLOWED_HOSTS), or the sign-in cannot be sealed (no AGRITRACE_ISSUER_KEK).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unavailable": {
                    "value": {
                      "error": "identity provider sign-in unavailable: no identity provider host is allowed (AGRITRACE_OIDC_ALLOWED_HOSTS)",
                      "code": "identity_provider_sign_in_unavailable"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/v1/auth/oidc/callback": {
      "post": {
        "operationId": "finishOidcSignIn",
        "summary": "Finish a sign-in with the company's identity provider",
        "description": "#87 (OpenID Connect). Anonymous, like login: the `state` and `code` the identity provider sent to the company's redirect URI (`{origin}/login/oidc/{company}`), with that company and the `iss` the provider added (RFC 9207, when it sends one), from the browser that started the sign-in (its `__Host-agt_oidc` cookie). The cookie must hold this state; the state is then used up first, whatever the outcome. The company must be the one the sign-in was started for, so a response from another company's provider is never redeemed with this one's (the mix-up attack). A sent `iss` must be the provider's issuer, and it is required when the provider's discovery document says `authorization_response_iss_parameter_supported`. The code is exchanged at the provider's token endpoint with the PKCE verifier and the client secret, and the ID token is verified: RS256 or ES256 only (`none` and HMAC are refused), a key of the provider's key set (fetched again when the key id is new, at most once a minute), the issuer, the audience (and `azp`), `exp`, `iat` and `nbf` with 60 seconds of tolerance, and the nonce of this sign-in. The provider's subject signs in the account linked to it; without a link, a verified email (`email_verified` true) of an existing account links that account. No account is ever created, and the account must be active and hold memberships of the provider's company only: a member of another company (a turned-off membership counts, since that company may turn it back on), a platform admin and a lab account are refused, and so is an account with no active membership. Two-step sign-in applies as after a password: an account with an authenticator app gets a login ticket (202) for POST /v1/auth/login/second-factor; otherwise the session opens (200) with no second factor proved. The audit row (`auth.login`, `method: oidc`, `linked`) commits with the link and the session or ticket; a refusal is `auth.login.oidc.failed`, naming the account only once the ID token verified. Every refusal is the same 401. Takes a token from the login rate-limit bucket before anything else. When an Origin header is sent it must be allowed. Not in SDK 0.2.0 (`x-not-in-sdk`): its bytes never change; a later SDK version adds it.",
        "tags": [
          "auth"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OidcCallback"
              },
              "example": {
                "state": "q3Vb0mXl2sQ",
                "code": "SplxlOBeZQQYbYS6WxSbIA",
                "company": "coop-dl",
                "iss": "https://login.coop.example"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Signed in. Send `csrf_token` as `X-CSRF-Token` on unsafe methods.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              },
              "Set-Cookie": {
                "$ref": "#/components/headers/Set-Cookie"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuthSession"
                },
                "example": {
                  "user": {
                    "id": 1,
                    "email": "alice@coop.example",
                    "display_name": "Alice"
                  },
                  "memberships": [
                    {
                      "tenant": "coop-dl",
                      "role": "tenant_admin",
                      "facilities": null,
                      "lab_id": null
                    }
                  ],
                  "csrf_token": "q3Vb0mXl2sQ"
                }
              }
            }
          },
          "202": {
            "description": "The account has two-step sign-in. No session and no cookie yet: send the ticket and a code to POST /v1/auth/login/second-factor.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SecondFactorChallenge"
                },
                "example": {
                  "second_factor": "required",
                  "ticket": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGl2",
                  "expires_at": 1790086700.0
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, `state`, `code` or `company` missing or not text, `iss` not text, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "required": {
                    "value": {
                      "error": "state, code and company are required",
                      "code": "state_code_and_company_are_required"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "The sign-in was refused: a state this browser did not start, a used or expired state, another company's redirect URI, an `iss` that is not the provider's (or missing when the provider sends it), a provider removed, turned off or changed since the start, a code the provider refused, an ID token that does not verify (malformed text included), no linked account and no verified, well-formed email of an existing account, or an account that is disabled, has no active membership, holds a membership of another company (a turned-off one too) or is a platform admin or lab account.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "identity provider sign-in refused",
                  "code": "identity_provider_sign_in_refused"
                }
              }
            }
          },
          "403": {
            "description": "The Origin header is present and not allowed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "origin not allowed",
                  "code": "origin_not_allowed"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "description": "Too many sign-in attempts from this client address (the login bucket). Nothing was checked; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "502": {
            "description": "The company's identity provider did not answer, or answered outside the rules (its discovery document or key set could not be read). The state is used up: a retry of the same callback is refused (401); start the sign-in again.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "identity provider unreachable",
                  "code": "identity_provider_unreachable"
                }
              }
            }
          },
          "503": {
            "description": "This deployment does not allow sign-in with an identity provider, or the client secret cannot be read (no AGRITRACE_ISSUER_KEK).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unavailable": {
                    "value": {
                      "error": "identity provider sign-in unavailable: no identity provider host is allowed (AGRITRACE_OIDC_ALLOWED_HOSTS)",
                      "code": "identity_provider_sign_in_unavailable"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/v1/company/identity-provider": {
      "get": {
        "operationId": "getCompanyIdentityProvider",
        "summary": "Read the company's identity provider",
        "description": "#87 (OpenID Connect). The selected company's identity provider for sign-in (never its client secret), the company's own redirect URI to register with it (`{origin}/login/oidc/{company}`), and whether this deployment allows such sign-in. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The provider.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IdentityProviderState"
                },
                "example": {
                  "available": true,
                  "redirect_uri": "https://txng.theio.vn/login/oidc/coop-dl",
                  "provider": {
                    "issuer": "https://login.coop.example",
                    "client_id": "croppath-console",
                    "enabled": true,
                    "created_at": 1790086400.0,
                    "updated_at": 1790086400.0,
                    "linked_accounts": 3
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "updateCompanyIdentityProvider",
        "summary": "Set up or change the company's identity provider",
        "description": "#87 (OpenID Connect). The company's people can then sign in with it (POST /v1/auth/oidc/start). The issuer must be an https:// URL on a host this deployment allows (AGRITRACE_OIDC_ALLOWED_HOSTS); its discovery document is fetched and checked first: it must name the issuer exactly, offer the authorization code flow, PKCE S256 (when it lists PKCE methods), RS256 or ES256 ID tokens and the client secret sent with HTTP Basic or in the form body, and its endpoints must be on allowed hosts. The client secret is stored only encrypted (AES-256-GCM under AGRITRACE_ISSUER_KEK) and never returned. A new issuer or client id removes the provider's account links and needs a new client secret (400 `client_secret_is_required` otherwise), so a stored secret is never sent to another provider. The discovery document is cached for an hour; after that a sign-in fetches it again and checks it by the same rules. Needs a password confirmed within the last 10 minutes and, for an account with two-step sign-in, a code within the last 5 (the step-up). Audited (`company.identity_provider.update`, in the same transaction; never the secret). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/IdentityProviderUpdate"
              },
              "example": {
                "issuer": "https://login.coop.example",
                "client_id": "croppath-console",
                "client_secret": "s3cret-from-the-idp",
                "enabled": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Saved.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IdentityProviderState"
                },
                "example": {
                  "available": true,
                  "redirect_uri": "https://txng.theio.vn/login/oidc/coop-dl",
                  "provider": {
                    "issuer": "https://login.coop.example",
                    "client_id": "croppath-console",
                    "enabled": true,
                    "created_at": 1790086400.0,
                    "updated_at": 1790086400.0,
                    "linked_accounts": 3
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a malformed or not allowed issuer, a malformed client id or secret, no client secret for a new provider, `enabled` not true or false, a provider whose discovery document could not be read or breaks the rules (`identity_provider_not_usable`, with a short reason), or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_fields": {
                    "value": {
                      "error": "unknown fields: extra",
                      "code": "unknown_fields"
                    }
                  },
                  "issuer": {
                    "value": {
                      "error": "invalid issuer: its host is not allowed",
                      "code": "invalid_issuer"
                    }
                  },
                  "secret": {
                    "value": {
                      "error": "client_secret is required",
                      "code": "client_secret_is_required"
                    }
                  },
                  "not_usable": {
                    "value": {
                      "error": "identity provider not usable: issuer_mismatch",
                      "code": "identity_provider_not_usable"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session that must confirm its password (`reauthentication_required`) or, with two-step sign-in, its password and a code (`mfa_step_up_required`) with POST /v1/auth/reauth, then repeat the request; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), or the company is leaving CropPath (read-only).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The company does not exist.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "503": {
            "description": "This deployment does not allow sign-in with an identity provider, or has no key-encryption key (AGRITRACE_ISSUER_KEK) to store the secret.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "unavailable": {
                    "value": {
                      "error": "identity provider sign-in unavailable: no identity provider host is allowed (AGRITRACE_OIDC_ALLOWED_HOSTS)",
                      "code": "identity_provider_sign_in_unavailable"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "delete": {
        "operationId": "removeCompanyIdentityProvider",
        "summary": "Remove the company's identity provider",
        "description": "#87 (OpenID Connect). Removes the provider and its account links; sign-ins in progress fail at their callback. The company's people sign in with their passwords (or passkeys) again. Sessions already open stay open. Needs a password confirmed within the last 10 minutes and, for an account with two-step sign-in, the step-up. Audited (`company.identity_provider.remove`, in the same transaction). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant: CropPath support) through a signed-in session only: an API token, an API client or the legacy token is refused (403); operators and auditors are refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): SDK 0.2.0 was released before it.",
        "tags": [
          "settings"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "204": {
            "description": "Removed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "$ref": "#/components/headers/Cache-Control"
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token; or a session that must confirm its password (`reauthentication_required`) or, with two-step sign-in, its password and a code (`mfa_step_up_required`) with POST /v1/auth/reauth, then repeat the request; nothing was done.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "reauthentication": {
                    "value": {
                      "error": "reauthentication required: confirm your password with POST /v1/auth/reauth",
                      "code": "reauthentication_required"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (only tenant_admin and platform_admin, through a signed-in session: an API token, an API client or the legacy token is refused), tenant not allowed (X-Tenant), two-factor required (this session must prove a second factor before acting for the company), or the company is leaving CropPath (read-only).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The company has no identity provider.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: identity provider",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/station-delegations": {
      "get": {
        "operationId": "listStationSignIns",
        "summary": "The pending and active station sign-ins at a gateway",
        "description": "#85 (owner decision 2026-10-17, option b): operators keep working at an edge station with the WAN down. The station sign-ins at the gateway that are pending (the code not typed yet, still valid) or active (claimed by the station, not ended, not revoked), the active ones first, each group newest first, at most 100 (an operator has at most 3 codes waiting at a station, so codes never push an active sign-in off the list): the caller's own, or every operator's for a company admin. Never the code. A gateway of another company, or out of an operator's facilities, answers like a missing one. Not audited (a read). Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) and for an operator within its facilities (the gateway's), through a signed-in session only: an API token, an API client or the legacy token is refused (403); auditors and labs are refused (403). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Gateway id (the edge station's).",
            "schema": {
              "type": "string"
            },
            "example": "gw-01"
          }
        ],
        "responses": {
          "200": {
            "description": "The sign-ins.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StationDelegationList"
                },
                "example": {
                  "items": [
                    {
                      "id": "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f",
                      "gateway": "gw-01",
                      "operator": "user-7",
                      "state": "active",
                      "issued_at": 1790560000.0,
                      "code_expires_at": 1790560600.0,
                      "expires_at": 1790588800.0,
                      "claimed_at": 1790560100.0,
                      "revoked_at": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (an auditor or a lab; or an API token, an OAuth2 access token or the legacy token: a station sign-in is a person's, through a signed-in session only), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway (or another company's, or out of the operator's facilities).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: gw-01",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createStationSignIn",
        "summary": "Sign in at an edge station (a one-time code to type there)",
        "description": "#85 (owner decision 2026-10-17, option b): operators keep working at an edge station with the WAN down. The signed-in person lets the gateway's edge station record offline actions (accept a fruit, re-measure it, print its labels) for them until `expires_at` (`lifetime_s`, 900 to 28800 seconds, default 28800: at most one shift). The answer carries a one-time `code` (8 characters, valid 10 minutes, shown only here; only its SHA-256 is kept; at most 3 waiting per person and station, else 409 `too_many_pending`) that the operator types on the station's screen; the station claims it with a request signed by its own key (POST /v1/gateways/{id}/station-delegations/claim). No credential reaches the station: it can only record actions that the cloud checks when the station replays them (POST /v1/gateways/{id}/station-actions), and they count at most as Device-recorded. Audited (`station.delegation.issue`, never the code) in the company's activity log. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) and for an operator within its facilities (the gateway's), through a signed-in session only: an API token, an API client or the legacy token is refused (403); auditors and labs are refused (403). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Gateway id (the edge station's).",
            "schema": {
              "type": "string"
            },
            "example": "gw-01"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StationSignInRequest"
              },
              "example": {
                "lifetime_s": 28800
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The sign-in, with its one-time code.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StationSignIn"
                },
                "example": {
                  "id": "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f",
                  "gateway": "gw-01",
                  "operator": "user-7",
                  "state": "pending",
                  "issued_at": 1790560000.0,
                  "code_expires_at": 1790560600.0,
                  "expires_at": 1790588800.0,
                  "claimed_at": null,
                  "revoked_at": null,
                  "code": "K7MQ2XPA"
                }
              }
            }
          },
          "400": {
            "description": "A bad body, a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "lifetime": {
                    "value": {
                      "error": "invalid lifetime_s: whole seconds from 900 to 28800",
                      "code": "invalid_lifetime_s"
                    }
                  },
                  "body": {
                    "value": {
                      "error": "invalid body: only lifetime_s",
                      "code": "invalid_body"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (an auditor or a lab; or an API token, an OAuth2 access token or the legacy token: a station sign-in is a person's, through a signed-in session only), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway (or another company's, or out of the operator's facilities).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: gw-01",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "The gateway is not active, or the caller already has 3 sign-in codes waiting (not typed yet, still valid) at this station (`too_many_pending`: type one or revoke one first). Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "gateway_inactive": {
                    "value": {
                      "error": "gateway inactive: the station's gateway is not active",
                      "code": "gateway_inactive"
                    }
                  },
                  "too_many_pending": {
                    "value": {
                      "error": "too many pending: 3 sign-in codes are already waiting at this station; type one or revoke one first",
                      "code": "too_many_pending"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/station-delegations/{id}/revoke": {
      "post": {
        "operationId": "revokeStationSignIn",
        "summary": "Revoke a station sign-in",
        "description": "#85 (owner decision 2026-10-17, option b): operators keep working at an edge station with the WAN down. Revokes a station sign-in: the operator's own, or any of the company's for a company admin. From then on the station records nothing more under it (it learns of it on its next sync or replay and ends the operator's local session), and no action it recorded under it and has not replayed yet is applied (403 `delegation_revoked`). Another operator's sign-in, another company's or one at a gateway out of the operator's facilities answers like a missing one; one already revoked is 409. Audited (`station.delegation.revoke`) in the company's activity log. Allowed for tenant_admin and platform_admin (acting for the company through X-Tenant) and for an operator within its facilities (the gateway's), through a signed-in session only: an API token, an API client or the legacy token is refused (403); auditors and labs are refused (403). Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "devices"
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "security": [
          {
            "cookie": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Station sign-in id.",
            "schema": {
              "type": "string"
            },
            "example": "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "Revoked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StationDelegation"
                },
                "example": {
                  "id": "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f",
                  "gateway": "gw-01",
                  "operator": "user-7",
                  "state": "revoked",
                  "issued_at": 1790560000.0,
                  "code_expires_at": 1790560600.0,
                  "expires_at": 1790588800.0,
                  "claimed_at": 1790560100.0,
                  "revoked_at": 1790570000.0
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (an auditor or a lab; or an API token, an OAuth2 access token or the legacy token: a station sign-in is a person's, through a signed-in session only), tenant not allowed (X-Tenant), origin not allowed or CSRF token missing or invalid.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sign-in for the caller.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "Already revoked. Or the Idempotency-Key's first request is still running (`Retry-After`), or it ran but its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "delegation_revoked": {
                    "value": {
                      "error": "delegation revoked: the station sign-in is already revoked",
                      "code": "delegation_revoked"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "idempotency_key_used": {
                    "value": {
                      "error": "idempotency key used: the response is too large to replay",
                      "code": "idempotency_key_used"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/station-delegations/claim": {
      "post": {
        "operationId": "claimStationSignIn",
        "summary": "An edge station claims an operator's sign-in",
        "description": "#85 (owner decision 2026-10-17, option b): operators keep working at an edge station with the WAN down. The station claims the sign-in whose one-time code the operator typed on its screen (any case; spaces and hyphens ignored): once, while the code is valid, only at the gateway it was issued for, and only while the operator's account is active and the operator may still record fruit actions at the station's facility (else 403 `operator_not_allowed`; disabling the account or turning the membership off revokes the sign-in: 404). The answer is the sign-in (the operator's opaque id and display name, its end), the label data of the fruits of the open lots at the station's facility (newest first, at most 2000), which its printer queue prints from with the WAN down, the highest `seq` the cloud recorded from the station (`last_seq`, which its action counter moves above) and the cloud's `time` (the station counts the sign-in's end from it on its monotonic clock). One audit row (`station.delegation.claim`, actor the operator) in the company's activity log. The body is signed with one of the gateway's own active keys (ES256 over the canonical JSON of every member but `sig`, as an envelope). Over mTLS the client certificate must be the gateway's. No principal: the signature is the authentication. #326: with `label_code=1` each label also has the fruit's lookup code (`label_code`, #288), the 15-character code the station's fruit label prints for a person whose QR code cannot be scanned; the scan page and `GET /v1/public/resolve` read it. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "ingest"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "deviceMtls": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Gateway id (the edge station's).",
            "schema": {
              "type": "string"
            },
            "example": "gw-01"
          },
          {
            "name": "label_code",
            "in": "query",
            "required": false,
            "description": "#326: `1` adds each label's lookup code (`labels[].label_code`), which the station's fruit label prints; `0` or none leaves it out and answers exactly as before; any other value is refused (400 `bad label_code`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StationClaimRequest"
              },
              "example": {
                "gateway": "gw-01",
                "time": "2026-09-28T08:40:00+07:00",
                "code": "K7MQ2XPA",
                "sig": {
                  "alg": "ES256",
                  "kid": "gw-01",
                  "value": "q6bJ0tM1g2pUo7k9wqzQyLhB4mF3aVxN8cR5sTdE1uYiHjKlZ0oP9nW2eQ3rT4yU6iO7pA8sD9fG0hJ1kL2zXc"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Claimed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StationClaim"
                },
                "example": {
                  "delegation": {
                    "id": "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f",
                    "operator": "user-7",
                    "name": "Lan",
                    "issued_at": 1790560000.0,
                    "claimed_at": 1790560100.0,
                    "expires_at": 1790588800.0
                  },
                  "labels": [
                    {
                      "code": "Q-014-0129",
                      "lot": "LO-260928-014",
                      "n": 129,
                      "round": 0,
                      "status": "recorded",
                      "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
                    }
                  ],
                  "last_seq": 41,
                  "time": 1790560100.0
                }
              }
            }
          },
          "400": {
            "description": "A malformed request, or `label_code` not 0 or 1.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "malformed": {
                    "value": {
                      "error": "malformed: the request's fields",
                      "code": "malformed"
                    }
                  },
                  "code": {
                    "value": {
                      "error": "bad code: the sign-in code shown in the console",
                      "code": "bad_code"
                    }
                  },
                  "bad_label_code": {
                    "value": {
                      "error": "bad label_code",
                      "code": "bad_label_code"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Refused: the signature is not from an active key of this gateway, a bad signature, an inactive gateway, a client certificate of another identity, a request more than 300 s off the server's time, or a company that is leaving CropPath. Or the operator may no longer record fruit actions at the station's facility (`operator_not_allowed`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key": {
                    "value": {
                      "error": "key not authorized: not an active key of this gateway",
                      "code": "key_not_authorized"
                    }
                  },
                  "signature": {
                    "value": {
                      "error": "bad signature",
                      "code": "bad_signature"
                    }
                  },
                  "stale": {
                    "value": {
                      "error": "stale request: the station's time is more than 300 s off",
                      "code": "stale_request"
                    }
                  },
                  "operator": {
                    "value": {
                      "error": "operator not allowed: the operator may no longer act for the company",
                      "code": "operator_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway, or no sign-in with this code waiting at this station (unknown, used, expired or revoked).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "unknown code: no sign-in with this code is waiting at this station",
                  "code": "unknown_code"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/station-sync": {
      "post": {
        "operationId": "syncStation",
        "summary": "An edge station asks the state of its sign-ins and its label data",
        "description": "#85 (owner decision 2026-10-17, option b): operators keep working at an edge station with the WAN down. Once it reaches the cloud, the station asks the state of the sign-ins it holds (`active`, `revoked`, `expired`, or `unknown` for one that is not this station's or never claimed; `revoked` too for one whose operator's account is disabled or who may no longer record fruit actions at the station's facility) and refreshes its label data and `last_seq`; it ends the local session of a sign-in that is no longer active. A read: no audit row. The body is signed with one of the gateway's own active keys (ES256 over the canonical JSON of every member but `sig`, as an envelope). Over mTLS the client certificate must be the gateway's. No principal: the signature is the authentication. #326: with `label_code=1` each label also has the fruit's lookup code (`label_code`, #288), the 15-character code the station's fruit label prints for a person whose QR code cannot be scanned; the scan page and `GET /v1/public/resolve` read it. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "ingest"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "deviceMtls": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Gateway id (the edge station's).",
            "schema": {
              "type": "string"
            },
            "example": "gw-01"
          },
          {
            "name": "label_code",
            "in": "query",
            "required": false,
            "description": "#326: `1` adds each label's lookup code (`labels[].label_code`), which the station's fruit label prints; `0` or none leaves it out and answers exactly as before; any other value is refused (400 `bad label_code`).",
            "schema": {
              "type": "string",
              "enum": [
                "0",
                "1"
              ]
            },
            "example": "1",
            "x-not-in-sdk": true
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StationSyncRequest"
              },
              "example": {
                "gateway": "gw-01",
                "time": "2026-09-28T10:00:00+07:00",
                "delegations": [
                  "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f"
                ],
                "sig": {
                  "alg": "ES256",
                  "kid": "gw-01",
                  "value": "q6bJ0tM1g2pUo7k9wqzQyLhB4mF3aVxN8cR5sTdE1uYiHjKlZ0oP9nW2eQ3rT4yU6iO7pA8sD9fG0hJ1kL2zXc"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The states and the labels.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StationSync"
                },
                "example": {
                  "delegations": {
                    "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f": "active"
                  },
                  "labels": [
                    {
                      "code": "Q-014-0129",
                      "lot": "LO-260928-014",
                      "n": 129,
                      "round": 0,
                      "status": "recorded",
                      "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
                    }
                  ],
                  "last_seq": 41,
                  "time": 1790564400.0
                }
              }
            }
          },
          "400": {
            "description": "A malformed request, or `label_code` not 0 or 1.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "malformed": {
                    "value": {
                      "error": "malformed: the request's fields",
                      "code": "malformed"
                    }
                  },
                  "ids": {
                    "value": {
                      "error": "bad delegations: at most 64 delegation ids",
                      "code": "bad_delegations"
                    }
                  },
                  "bad_label_code": {
                    "value": {
                      "error": "bad label_code",
                      "code": "bad_label_code"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Refused: the signature is not from an active key of this gateway, a bad signature, an inactive gateway, a client certificate of another identity, a request more than 300 s off the server's time, or a company that is leaving CropPath.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key": {
                    "value": {
                      "error": "key not authorized: not an active key of this gateway",
                      "code": "key_not_authorized"
                    }
                  },
                  "signature": {
                    "value": {
                      "error": "bad signature",
                      "code": "bad_signature"
                    }
                  },
                  "stale": {
                    "value": {
                      "error": "stale request: the station's time is more than 300 s off",
                      "code": "stale_request"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: gw-01",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/gateways/{id}/station-actions": {
      "post": {
        "operationId": "replayStationAction",
        "summary": "An edge station replays an operator's offline action",
        "description": "#85 (owner decision 2026-10-17, option b): operators keep working at an edge station with the WAN down. One action an operator recorded at the station with the WAN down, signed by the station as recorded offline at station X for operator Y, replayed in the station's order once it is back: `accept` and `remeasure` are applied as that operator's fruit actions with every existing check (lot closed or sampled, transition, measurement in review), the record `id` as idempotency key and no set_session push; `print` records that the station printed the fruit's label from its local queue. The cloud checks that the sign-in is this station's and of this company (else 404 like a missing one), claimed, not revoked, the record's time within it (300 s of slack; for a record stamped `time_source` `unsynced`, its `since_claim_s` alone, required: else 403 `unsynced_clock`), `since_claim_s` within the sign-in's length (300 s of slack) and the replay within 72 hours of its end (else 403), that the operator may still act on the fruit's facility, which must be the station's (403, 404), that `seq` is above every action the cloud recorded from the station (409 `out_of_order`), and that every envelope named in `after` is stored or was rejected (else 503 `not_stored_yet`, Retry-After: the station tries again, so an acceptance never overtakes the knock it accepts). A re-measure's offline `round` must be the fruit's next round: otherwise 409 `round_conflict`, nothing changes on the fruit, the conflict is recorded, and the knocks the station's devices stamped with that round do not bind (`superseded_round`). The same record again answers what it answered the first time (200 for an applied one) and writes nothing; other content under a stored id is 409 `id_conflict`. Each recorded action writes exactly one audit row (`station.action`, actor the operator, `after.station` the gateway). A fruit with an accept or re-measure from a station is at most Device-recorded (ADR 0001). The body is signed with one of the gateway's own active keys (ES256 over the canonical JSON of every member but `sig`, as an envelope). Over mTLS the client certificate must be the gateway's. No principal: the signature is the authentication. Added after the partner SDK 0.2.0 (`x-not-in-sdk`): not part of the generated SDK clients.",
        "tags": [
          "ingest"
        ],
        "x-not-in-sdk": true,
        "security": [
          {
            "deviceMtls": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Gateway id (the edge station's).",
            "schema": {
              "type": "string"
            },
            "example": "gw-01"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StationActionRecord"
              },
              "example": {
                "v": 1,
                "id": "9b2e4c1a-7f3d-4e8b-a6c5-0d1e2f3a4b5c",
                "type": "remeasure",
                "gateway": "gw-01",
                "seq": 12,
                "delegation": "3f9c2b1e8a7d4c6b9e0f1a2b3c4d5e6f",
                "operator": "user-7",
                "fruit": "Q-014-0129",
                "round": 1,
                "recorded_at": "2026-09-28T09:12:03.120+07:00",
                "time_source": "ntp",
                "after": [
                  "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30"
                ],
                "sig": {
                  "alg": "ES256",
                  "kid": "gw-01",
                  "value": "q6bJ0tM1g2pUo7k9wqzQyLhB4mF3aVxN8cR5sTdE1uYiHjKlZ0oP9nW2eQ3rT4yU6iO7pA8sD9fG0hJ1kL2zXc"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Applied before (a lost acknowledgement): the stored answer.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StationActionResult"
                },
                "example": {
                  "id": "9b2e4c1a-7f3d-4e8b-a6c5-0d1e2f3a4b5c",
                  "type": "accept",
                  "outcome": "applied",
                  "seq": 11,
                  "fruit": {
                    "code": "Q-014-0129",
                    "status": "recorded",
                    "accepted_at": 1790561523.0,
                    "round": 0
                  }
                }
              }
            }
          },
          "201": {
            "description": "Applied.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StationActionResult"
                },
                "example": {
                  "id": "9b2e4c1a-7f3d-4e8b-a6c5-0d1e2f3a4b5c",
                  "type": "remeasure",
                  "outcome": "applied",
                  "seq": 12,
                  "fruit": {
                    "code": "Q-014-0129",
                    "status": "awaiting_device",
                    "accepted_at": null,
                    "round": 1
                  }
                }
              }
            }
          },
          "400": {
            "description": "A malformed record.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "malformed": {
                    "value": {
                      "error": "malformed: round",
                      "code": "malformed"
                    }
                  },
                  "gateway": {
                    "value": {
                      "error": "gateway mismatch: the request names another gateway",
                      "code": "gateway_mismatch"
                    }
                  },
                  "future": {
                    "value": {
                      "error": "future timestamp: recorded after the server's time",
                      "code": "future_timestamp"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Refused: the station's key or the sign-in (expired, by `recorded_at` or by `since_claim_s`; revoked, also by disabling the operator's account or turning their membership off; not claimed; not active when recorded; another operator), a record stamped `unsynced` without `since_claim_s` (`unsynced_clock`), or the operator may no longer act for the company (the account disabled included).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "key": {
                    "value": {
                      "error": "key not authorized: not an active key of this gateway",
                      "code": "key_not_authorized"
                    }
                  },
                  "expired": {
                    "value": {
                      "error": "delegation expired",
                      "code": "delegation_expired"
                    }
                  },
                  "revoked": {
                    "value": {
                      "error": "delegation revoked",
                      "code": "delegation_revoked"
                    }
                  },
                  "unsynced": {
                    "value": {
                      "error": "unsynced clock: the station's clock was off and the action carries no since_claim_s",
                      "code": "unsynced_clock"
                    }
                  },
                  "operator": {
                    "value": {
                      "error": "operator not allowed: the operator may no longer act for the company",
                      "code": "operator_not_allowed"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such gateway, no such sign-in at this station (another station's or another company's), or no such fruit at this station.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "delegation": {
                    "value": {
                      "error": "not found: no such delegation at this station",
                      "code": "not_found"
                    }
                  },
                  "fruit": {
                    "value": {
                      "error": "not found: no such fruit at this station",
                      "code": "not_found"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "description": "Not applied: a round conflict (recorded; the same record again answers it again), an action replayed out of the station's order, another record under the id, or a check of the fruit action (lot closed, transition, review).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "round": {
                    "value": {
                      "error": "round conflict: the station numbered round 1, the fruit's next round is 2",
                      "code": "round_conflict"
                    }
                  },
                  "order": {
                    "value": {
                      "error": "out of order: the station already replayed action 12",
                      "code": "out_of_order"
                    }
                  },
                  "id": {
                    "value": {
                      "error": "id conflict: another record is stored under this id",
                      "code": "id_conflict"
                    }
                  },
                  "transition": {
                    "value": {
                      "error": "invalid transition: awaiting_device to accept",
                      "code": "invalid_transition"
                    }
                  }
                }
              }
            }
          },
          "413": {
            "description": "Over 8192 bytes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too large: at most 8192 bytes",
                  "code": "too_large"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "An envelope the action follows is not stored yet; try again later.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not stored yet: an envelope the action follows has not reached the cloud",
                  "code": "not_stored_yet"
                }
              }
            }
          }
        }
      }
    },
    "/v1/admin-units": {
      "get": {
        "operationId": "getAdminUnits",
        "summary": "Viet Nam's provinces, or one province's communes, by official code",
        "description": "#273: the official list of Viet Nam's administrative units, two levels since 1 July 2025: provinces (tỉnh, thành phố trung ương; 2-digit codes) and communes (xã, phường, đặc khu; 5-digit codes), as the National Statistics Office publishes them (Decision 19/2025/QĐ-TTg). Without `province` the answer lists the provinces; with `province` that province's communes. A commune belongs to the province the list names, never to the one its code's digits suggest. The list changes when a resolution merges, splits or renames units, so it is versioned: by default the version in force on Viet Nam's date today (Asia/Ho_Chi_Minh), or the one `version` names (an older version, to show an address coded from it). A code alone never names a unit: codes were reused across the 2025 reform, so a stored code always goes with its `version`. Unit names and kinds are the official Vietnamese ones in every language. Reference data, no personal data: anonymous and the same bytes for every visitor; cacheable for an hour with a strong ETag, and a matching `If-None-Match` answers 304. Not audited (a read). Rate limited per client before anything else (the /v1/public/* bucket: bursts of 60, then 20 a second). Not part of the partner SDK clients (`x-not-in-sdk`). Bounded work: in-memory lookups, no database statement.",
        "tags": [
          "registry"
        ],
        "security": [],
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "province",
            "in": "query",
            "required": false,
            "description": "A province's 2-digit official code: answer its communes instead of the provinces. A code that is not a province of the version answers 404; anything but two ASCII digits 400.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{2}$"
            },
            "example": "82"
          },
          {
            "name": "version",
            "in": "query",
            "required": false,
            "description": "A catalog version, `vn-` and the date of its list (as every answer's `version` gives it): read that version instead of the one in force today. An unknown version answers 404; another shape 400.",
            "schema": {
              "type": "string",
              "pattern": "^vn-[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "vn-2026-10-17"
          },
          {
            "name": "If-None-Match",
            "in": "header",
            "required": false,
            "description": "An ETag of an earlier answer (quoted), a list of them or `*`; compared weakly (RFC 9110). When it names the version's tag the answer is 304.",
            "schema": {
              "type": "string"
            },
            "example": "\"6c1f0e9a4b2d8c7e5f3a1b0d9c8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e\""
          }
        ],
        "responses": {
          "200": {
            "description": "The provinces of the version (`AdminUnitProvinces`), or the communes of the province asked (`AdminUnitCommunes`; an empty list for a province without communes in that version).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=3600`: browsers (and any shared cache that honours it) keep it an hour, then revalidate with the ETag. Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The SHA-256 hex of the catalog version's data file, quoted (a strong ETag). Every answer of one version carries the same tag; a new version has another.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/AdminUnitProvinces"
                    },
                    {
                      "$ref": "#/components/schemas/AdminUnitCommunes"
                    }
                  ]
                },
                "examples": {
                  "provinces": {
                    "summary": "The provinces (two of 34 shown)",
                    "value": {
                      "version": "vn-2026-10-17",
                      "valid_from": "2026-09-20",
                      "source": {
                        "publisher": "National Statistics Office of Viet Nam (Cục Thống kê, Ministry of Finance)",
                        "url": "https://danhmuchanhchinh.nso.gov.vn/"
                      },
                      "provinces": [
                        {
                          "code": "01",
                          "name": "Thành phố Hà Nội",
                          "kind": "thành phố trung ương"
                        },
                        {
                          "code": "82",
                          "name": "Tỉnh Đồng Tháp",
                          "kind": "tỉnh"
                        }
                      ]
                    }
                  },
                  "communes": {
                    "summary": "The communes of province 82 (two shown)",
                    "value": {
                      "version": "vn-2026-10-17",
                      "valid_from": "2026-09-20",
                      "source": {
                        "publisher": "National Statistics Office of Viet Nam (Cục Thống kê, Ministry of Finance)",
                        "url": "https://danhmuchanhchinh.nso.gov.vn/"
                      },
                      "province": {
                        "code": "82",
                        "name": "Tỉnh Đồng Tháp",
                        "kind": "tỉnh"
                      },
                      "communes": [
                        {
                          "code": "28439",
                          "name": "Phường Cai Lậy",
                          "kind": "phường"
                        },
                        {
                          "code": "28516",
                          "name": "Xã Ngũ Hiệp",
                          "kind": "xã"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "304": {
            "description": "Not modified: the request's `If-None-Match` names the version's ETag. No body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=3600`, as on the 200.",
                "schema": {
                  "type": "string"
                }
              },
              "ETag": {
                "description": "The version's ETag, as on the 200.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "400": {
            "description": "`bad_province`: `province` is not two ASCII digits; `bad_version`: `version` is not `vn-` and a date; `bad_request_id`: the X-Request-Id header is malformed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`: never cached.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad province",
                  "code": "bad_province"
                }
              }
            }
          },
          "404": {
            "description": "Not a province of the version, or not a version this server has. Every such request gets this same body and headers, held to the same minimum time; the code is never echoed. Answered so even when `If-None-Match` names the version's tag.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`public, max-age=0, s-maxage=60` (a 404 is never served stale). Never `Set-Cookie`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: admin-units",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "429": {
            "description": "Too many requests from this client address (the per-IP token bucket the /v1/public/* routes share: bursts of 60, then 20 a second). The address is the `CF-Connecting-IP` a trusted proxy (AGRITRACE_TRUSTED_PROXIES) sends, else the socket peer. Nothing else was done; retry after `Retry-After` seconds.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`: a refusal is never cached.",
                "schema": {
                  "type": "string"
                }
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "too many requests",
                  "code": "too_many_requests"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "No catalog is installed on this server, or none of its versions is in force yet on Viet Nam's date (a version named by `version` is still served). Never cached; retry later.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              },
              "Retry-After": {
                "$ref": "#/components/headers/Retry-After"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "administrative units catalog unavailable",
                  "code": "administrative_units_catalog_unavailable"
                }
              }
            }
          }
        }
      }
    },
    "/v1/agronomists": {
      "get": {
        "operationId": "listAgronomists",
        "summary": "List the agronomist registry",
        "description": "#351. The platform's agronomist registry, newest first: every row for a platform admin; for an agronomist, their own row only. Personal data: `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "verified",
                "suspended"
              ]
            },
            "example": "pending",
            "description": "Only rows of this status."
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "description": "Only rows with a smaller id: the previous page's `next_before`.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "41"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "At most this many items (1 to 200; 100 by default).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "A page of rows.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomistPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 3,
                      "user_id": 41,
                      "email": "agronomist@coop.example",
                      "legal_name": "Nguyễn Văn An",
                      "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                      "qualification": "Kỹ sư nông học",
                      "contact": "agronomist@coop.example",
                      "note": null,
                      "status": "verified",
                      "created_at": 1790000000.5,
                      "updated_at": 1790003600.5,
                      "verified_by": "support@croppath.example",
                      "verified_at": 1790003600.5,
                      "suspended_by": null,
                      "suspended_at": null,
                      "suspend_reason": null
                    }
                  ],
                  "next_before": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a bad `status`, `before` or `limit`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "status": {
                    "value": {
                      "error": "invalid status: one of pending, verified, suspended",
                      "code": "invalid_status"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin or agronomist, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createAgronomist",
        "summary": "Register an agronomist (pending)",
        "description": "#351. A platform admin registers the account of `email` as an agronomist, `pending` until verified (POST .../verify) after an identity and qualification check made outside the platform. Audited (`agronomist.create`: the row, the account and the status; never the legal name or contact). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgronomistCreate"
              },
              "example": {
                "email": "agronomist@coop.example",
                "legal_name": "Nguyễn Văn An",
                "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                "qualification": "Kỹ sư nông học"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The row as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Agronomist"
                },
                "example": {
                  "id": 3,
                  "user_id": 41,
                  "email": "agronomist@coop.example",
                  "legal_name": "Nguyễn Văn An",
                  "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                  "qualification": "Kỹ sư nông học",
                  "contact": "agronomist@coop.example",
                  "note": null,
                  "status": "pending",
                  "created_at": 1790000000.5,
                  "updated_at": 1790003600.5,
                  "verified_by": null,
                  "verified_at": null,
                  "suspended_by": null,
                  "suspended_at": null,
                  "suspend_reason": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a bad value, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: status",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No account has this email.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: user",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The account already has a registry row. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "already_registered": {
                    "value": {
                      "error": "already registered: this account already has an agronomist record",
                      "code": "already_registered"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/agronomists/{id}": {
      "get": {
        "operationId": "getAgronomist",
        "summary": "Read an agronomist's registry row",
        "description": "#351. One row: a platform admin any; an agronomist only their own (another answers 404). `no-store`. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          }
        ],
        "responses": {
          "200": {
            "description": "The row.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Agronomist"
                },
                "example": {
                  "id": 3,
                  "user_id": 41,
                  "email": "agronomist@coop.example",
                  "legal_name": "Nguyễn Văn An",
                  "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                  "qualification": "Kỹ sư nông học",
                  "contact": "agronomist@coop.example",
                  "note": null,
                  "status": "verified",
                  "created_at": 1790000000.5,
                  "updated_at": 1790003600.5,
                  "verified_by": "support@croppath.example",
                  "verified_at": 1790003600.5,
                  "suspended_by": null,
                  "suspended_at": null,
                  "suspend_reason": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin or agronomist, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such row (or not the caller's).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/agronomists/{id}/verify": {
      "post": {
        "operationId": "verifyAgronomist",
        "summary": "Verify an agronomist",
        "description": "#351. A platform admin verifies the row (pending or suspended) once they checked the person's identity and qualification outside the platform: from then on the person may sign their companies' sheets. Four eyes: the platform admin who registered the row, the row's own account, and the platform admin whose reset of the account's two-step sign-in sent the row back to pending (its `suspended_by`), never verify it (409 `four_eyes_required`); another platform admin does. Needs a recent password and second-factor proof (#87 step-up). Audited (`agronomist.verify`: the row, the account and the status before and after). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgronomistVerify"
              },
              "example": {
                "note": "Identity card and degree checked on 2026-10-20"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The row as decided.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Agronomist"
                },
                "example": {
                  "id": 3,
                  "user_id": 41,
                  "email": "agronomist@coop.example",
                  "legal_name": "Nguyễn Văn An",
                  "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                  "qualification": "Kỹ sư nông học",
                  "contact": "agronomist@coop.example",
                  "note": null,
                  "status": "verified",
                  "created_at": 1790000000.5,
                  "updated_at": 1790003600.5,
                  "verified_by": "support@croppath.example",
                  "verified_at": 1790003600.5,
                  "suspended_by": null,
                  "suspended_at": null,
                  "suspend_reason": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a bad value, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: status",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such row.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The row already has this status, or the caller registered the row or is its account (four eyes). Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "already_verified": {
                    "value": {
                      "error": "already verified: this agronomist is verified",
                      "code": "already_verified"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  },
                  "four_eyes_required": {
                    "value": {
                      "error": "four eyes required: another platform admin verifies an agronomist, never the one who registered them, the one who reset their two-step sign-in, nor the agronomist themselves",
                      "code": "four_eyes_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/agronomists/{id}/suspend": {
      "post": {
        "operationId": "suspendAgronomist",
        "summary": "Suspend an agronomist",
        "description": "#351. A platform admin suspends the row, with a reason: the person signs nothing from then on; sheets they signed stay signed, and any admin of their company may revoke them. Needs a recent password and second-factor proof (#87 step-up). Audited (`agronomist.suspend`: the row, the account and the status before and after). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgronomistSuspend"
              },
              "example": {
                "reason": "Qualification withdrawn"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The row as decided.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Agronomist"
                },
                "example": {
                  "id": 3,
                  "user_id": 41,
                  "email": "agronomist@coop.example",
                  "legal_name": "Nguyễn Văn An",
                  "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                  "qualification": "Kỹ sư nông học",
                  "contact": "agronomist@coop.example",
                  "note": null,
                  "status": "suspended",
                  "created_at": 1790000000.5,
                  "updated_at": 1790003600.5,
                  "verified_by": "support@croppath.example",
                  "verified_at": 1790003600.5,
                  "suspended_by": "support@croppath.example",
                  "suspended_at": 1790090000.5,
                  "suspend_reason": "Qualification withdrawn"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a bad value, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: status",
                      "code": "unknown_field"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (platform_admin, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such row.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 3",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The row already has this status. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "already_suspended": {
                    "value": {
                      "error": "already suspended: this agronomist is suspended",
                      "code": "already_suspended"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/agronomy-sheets": {
      "get": {
        "operationId": "listAgronomySheets",
        "summary": "List the company's agronomic input sheets",
        "description": "#351. The company's sheets, newest first, without their bodies. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "crop",
            "in": "query",
            "required": false,
            "description": "Only sheets of this crop code.",
            "schema": {
              "type": "string"
            },
            "example": "durian"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only sheets of this status.",
            "schema": {
              "type": "string",
              "enum": [
                "draft",
                "signed",
                "superseded",
                "revoked"
              ]
            },
            "example": "signed"
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "description": "Only rows with a smaller id: the previous page's `next_before`.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "41"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "At most this many items (1 to 200; 100 by default).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "A page of sheets.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheetPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 7,
                      "series_key": "durian:Ri6:82",
                      "crop": "durian",
                      "variety": "Ri6",
                      "province_code": "82",
                      "version": 2,
                      "status": "draft",
                      "valid_from": "2027-01-01",
                      "valid_to": "2027-06-30",
                      "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                      "created_at": 1790000000.5,
                      "updated_at": 1790000600.5,
                      "signed_at": null,
                      "superseded_at": null,
                      "revoked_at": null,
                      "signed_by": null
                    }
                  ],
                  "next_before": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a bad `crop`, `status`, `before` or `limit`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "status": {
                    "value": {
                      "error": "invalid status: one of draft, signed, superseded, revoked",
                      "code": "invalid_status"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, agronomist or operator of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createAgronomySheet",
        "summary": "Create a draft agronomic input sheet",
        "description": "#351. A draft of the series the body names (crop of the crop registry, variety or `*`, province code or `*`), with that series' next version. Every value is optional in a draft and none has a default (CropPath ships no agronomic number); a value outside its sanity bounds, an unknown member and any member named `g_per_l` are refused. Audited (`agronomy_sheet.create`: the series, version and hash). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgronomySheetCreate"
              },
              "example": {
                "crop": "durian",
                "variety": "Ri6",
                "province_code": "82",
                "valid_from": "2027-01-01",
                "valid_to": "2027-06-30",
                "body": {
                  "stages": [
                    {
                      "code": "flowering",
                      "name": {
                        "vi": "Ra hoa",
                        "en": "Flowering",
                        "zh-Hans": "开花期"
                      },
                      "start": "2027-01-01",
                      "end": "2027-02-15"
                    }
                  ],
                  "references": [
                    {
                      "title": "Agronomist's field notes, season 2027"
                    }
                  ]
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The draft as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "ETag": {
                "description": "The sheet's `body_sha256`, quoted: send it back in If-Match to edit the draft.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheet"
                },
                "example": {
                  "id": 7,
                  "series_key": "durian:Ri6:82",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province_code": "82",
                  "version": 1,
                  "status": "draft",
                  "valid_from": "2027-01-01",
                  "valid_to": "2027-06-30",
                  "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                  "created_by": "agronomist@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "agronomist@coop.example",
                  "updated_at": 1790000600.5,
                  "copied_from_id": null,
                  "supersedes_id": null,
                  "superseded_by_id": null,
                  "signed_at": null,
                  "superseded_at": null,
                  "revoked_at": null,
                  "revoked_by": null,
                  "revoke_reason": null,
                  "body": {
                    "stages": [
                      {
                        "code": "flowering",
                        "name": {
                          "vi": "Ra hoa",
                          "en": "Flowering",
                          "zh-Hans": "开花期"
                        },
                        "start": "2027-01-01",
                        "end": "2027-02-15"
                      }
                    ],
                    "references": [
                      {
                        "title": "Agronomist's field notes, season 2027"
                      }
                    ]
                  },
                  "attestation": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, a bad value or an unknown crop, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: stages[0].kc: 3 is outside the sanity bounds 0 to 2",
                      "code": "invalid_body"
                    }
                  },
                  "g_per_l_refused": {
                    "value": {
                      "error": "g per l refused: salinity is electrical conductivity in mS/cm only; g/L is never used or converted",
                      "code": "g_per_l_refused"
                    }
                  },
                  "unknown_crop": {
                    "value": {
                      "error": "unknown crop: not in the crop registry",
                      "code": "unknown_crop"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or agronomist of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The company does not exist (a platform admin may name any with X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/agronomy-sheets/{id}": {
      "get": {
        "operationId": "getAgronomySheet",
        "summary": "Read an agronomic input sheet",
        "description": "#351. One sheet with its body and its signature (null until signed); its ETag is the quoted `body_sha256`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          }
        ],
        "responses": {
          "200": {
            "description": "The sheet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "ETag": {
                "description": "The sheet's `body_sha256`, quoted: send it back in If-Match to edit the draft.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheet"
                },
                "example": {
                  "id": 7,
                  "series_key": "durian:Ri6:82",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province_code": "82",
                  "version": 2,
                  "status": "signed",
                  "valid_from": "2027-01-01",
                  "valid_to": "2027-06-30",
                  "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                  "created_by": "agronomist@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "agronomist@coop.example",
                  "updated_at": 1790000600.5,
                  "copied_from_id": null,
                  "supersedes_id": 4,
                  "superseded_by_id": null,
                  "signed_at": 1790007200.5,
                  "superseded_at": null,
                  "revoked_at": null,
                  "revoked_by": null,
                  "revoke_reason": null,
                  "body": {
                    "stages": [
                      {
                        "code": "flowering",
                        "name": {
                          "vi": "Ra hoa",
                          "en": "Flowering",
                          "zh-Hans": "开花期"
                        },
                        "start": "2027-01-01",
                        "end": "2027-02-15"
                      }
                    ],
                    "references": [
                      {
                        "title": "Agronomist's field notes, season 2027"
                      }
                    ]
                  },
                  "attestation": {
                    "id": 5,
                    "agronomist_id": 3,
                    "user_id": 41,
                    "legal_name": "Nguyễn Văn An",
                    "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                    "statement_version": "1",
                    "statement_text_sha256": "9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "signed_at": 1790007200.5,
                    "second_factor_at": 1790007000.5
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, agronomist or operator of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sheet of this company: another company's answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "updateAgronomySheet",
        "summary": "Edit a draft agronomic input sheet",
        "description": "#351. A draft's validity and body (each member given replaces it), under If-Match: the sheet's `body_sha256` as last read. A signed, superseded or revoked sheet never changes (409; the database refuses it too): copy it into a new draft instead. Audited (`agronomy_sheet.update`: the fields and the hash before and after). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          },
          {
            "name": "If-Match",
            "in": "header",
            "required": true,
            "description": "The sheet's `body_sha256` as the caller last read it (its ETag, quoted or not): an edit made since answers 412 and changes nothing. A strong tag only: If-Match compares strongly (RFC 9110), so a weak tag (`W/\"...\"`) never matches and answers 412.",
            "schema": {
              "type": "string"
            },
            "example": "\"4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e\""
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgronomySheetUpdate"
              },
              "example": {
                "valid_to": "2027-07-31",
                "body": {
                  "stages": [
                    {
                      "code": "flowering",
                      "name": {
                        "vi": "Ra hoa",
                        "en": "Flowering",
                        "zh-Hans": "开花期"
                      },
                      "start": "2027-01-01",
                      "end": "2027-02-15"
                    }
                  ],
                  "references": [
                    {
                      "title": "Agronomist's field notes, season 2027"
                    }
                  ]
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The draft as stored.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "ETag": {
                "description": "The sheet's `body_sha256`, quoted: send it back in If-Match to edit the draft.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheet"
                },
                "example": {
                  "id": 7,
                  "series_key": "durian:Ri6:82",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province_code": "82",
                  "version": 2,
                  "status": "draft",
                  "valid_from": "2027-01-01",
                  "valid_to": "2027-06-30",
                  "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                  "created_by": "agronomist@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "agronomist@coop.example",
                  "updated_at": 1790000600.5,
                  "copied_from_id": 6,
                  "supersedes_id": null,
                  "superseded_by_id": null,
                  "signed_at": null,
                  "superseded_at": null,
                  "revoked_at": null,
                  "revoked_by": null,
                  "revoke_reason": null,
                  "body": {
                    "stages": [
                      {
                        "code": "flowering",
                        "name": {
                          "vi": "Ra hoa",
                          "en": "Flowering",
                          "zh-Hans": "开花期"
                        },
                        "start": "2027-01-01",
                        "end": "2027-02-15"
                      }
                    ],
                    "references": [
                      {
                        "title": "Agronomist's field notes, season 2027"
                      }
                    ]
                  },
                  "attestation": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a bad value, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body": {
                    "value": {
                      "error": "invalid body: stages[0].kc: 3 is outside the sanity bounds 0 to 2",
                      "code": "invalid_body"
                    }
                  },
                  "g_per_l_refused": {
                    "value": {
                      "error": "g per l refused: salinity is electrical conductivity in mS/cm only; g/L is never used or converted",
                      "code": "g_per_l_refused"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or agronomist of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sheet of this company: another company's answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The sheet is not a draft.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not draft: only a draft sheet is edited or signed",
                  "code": "not_draft"
                }
              }
            }
          },
          "412": {
            "description": "If-Match is not the sheet's hash: it changed since it was read, or the tag was sent weak (`W/`); nothing was changed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "precondition_failed": {
                    "value": {
                      "error": "precondition failed: the sheet's hash is not the one in If-Match; read it again",
                      "code": "precondition_failed"
                    }
                  },
                  "weak_etag": {
                    "value": {
                      "error": "precondition failed: a weak entity tag (W/) never matches, as If-Match compares strongly (RFC 9110); send the sheet's body_sha256",
                      "code": "precondition_failed"
                    }
                  }
                }
              }
            }
          },
          "428": {
            "description": "No If-Match header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "if-match required: send the sheet's body_sha256 in If-Match",
                  "code": "if_match_required"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/agronomy-sheets/{id}/document": {
      "get": {
        "operationId": "getAgronomySheetDocument",
        "summary": "Read the document a signature covers",
        "description": "#351. The RFC 8785 (JCS) text of {spec, tenant, series_key, version, valid_from, valid_to, body}, its SHA-256 (the sheet's `body_sha256`) and the statement an agronomist agrees to when signing, with its SHA-256. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          }
        ],
        "responses": {
          "200": {
            "description": "The document.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheetDocument"
                },
                "example": {
                  "id": 7,
                  "spec": "agritrace.agronomy-sheet/1",
                  "document": "{\"body\":{},\"series_key\":\"durian:Ri6:82\",\"spec\":\"agritrace.agronomy-sheet/1\",\"tenant\":\"coop-dl\",\"valid_from\":\"2027-01-01\",\"valid_to\":\"2027-06-30\",\"version\":2}",
                  "sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                  "statement": {
                    "version": "1",
                    "text": {
                      "vi": "Tôi, kỹ sư nông học có tên dưới đây, ...",
                      "en": "I, the agronomist named here, ...",
                      "zh-Hans": "本人（下列署名的农艺师）..."
                    },
                    "sha256": "9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a"
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, agronomist or operator of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sheet of this company: another company's answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/agronomy-sheets/{id}/sign": {
      "post": {
        "operationId": "signAgronomySheet",
        "summary": "Sign a draft agronomic input sheet",
        "description": "#351 (ADR 0014). A verified agronomist of the company signs a draft: an in-app attestation over the document's SHA-256, not a detached digital signature. The caller holds the role agronomist and no admin role in the company (separation of duties), has two-step sign-in on and proved a password and a code recently (#87 step-up), and CropPath verified them (the registry). The body names the hash the agronomist saw and the statement version they agree to; the server recomputes the hash (409 `sheet_changed` when the sheet changed) and checks the sheet is complete (stages, values given in every stage, windows and sections whole, inside the validity) and not over. In one transaction: the series' signed version becomes superseded, the sheet signed and its attestation and audit row (`agronomy_sheet.sign`) written. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgronomySheetSign"
              },
              "example": {
                "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                "statement_version": "1"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The signed sheet with its attestation.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheet"
                },
                "example": {
                  "id": 7,
                  "series_key": "durian:Ri6:82",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province_code": "82",
                  "version": 2,
                  "status": "signed",
                  "valid_from": "2027-01-01",
                  "valid_to": "2027-06-30",
                  "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                  "created_by": "agronomist@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "agronomist@coop.example",
                  "updated_at": 1790000600.5,
                  "copied_from_id": null,
                  "supersedes_id": 4,
                  "superseded_by_id": null,
                  "signed_at": 1790007200.5,
                  "superseded_at": null,
                  "revoked_at": null,
                  "revoked_by": null,
                  "revoke_reason": null,
                  "body": {
                    "stages": [
                      {
                        "code": "flowering",
                        "name": {
                          "vi": "Ra hoa",
                          "en": "Flowering",
                          "zh-Hans": "开花期"
                        },
                        "start": "2027-01-01",
                        "end": "2027-02-15"
                      }
                    ],
                    "references": [
                      {
                        "title": "Agronomist's field notes, season 2027"
                      }
                    ]
                  },
                  "attestation": {
                    "id": 5,
                    "agronomist_id": 3,
                    "user_id": 41,
                    "legal_name": "Nguyễn Văn An",
                    "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                    "statement_version": "1",
                    "statement_text_sha256": "9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "signed_at": 1790007200.5,
                    "second_factor_at": 1790007000.5
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a bad hash, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_body_sha256": {
                    "value": {
                      "error": "invalid body_sha256: the SHA-256 of the sheet's document in lower-case hex",
                      "code": "invalid_body_sha256"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (agronomist, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left); separation of duties; agronomist not verified.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  },
                  "separation_of_duties": {
                    "value": {
                      "error": "separation of duties: an admin of the company enables what an agronomist signed, never signs",
                      "code": "separation_of_duties"
                    }
                  },
                  "agronomist_not_verified": {
                    "value": {
                      "error": "agronomist not verified: CropPath has not verified this agronomist, or suspended them",
                      "code": "agronomist_not_verified"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sheet of this company: another company's answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The sheet changed since it was read, is not a draft, is incomplete or over, a later version of its series is signed, or the statement version is not the current one. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "sheet_changed": {
                    "value": {
                      "error": "sheet changed: the sheet's hash is not the one sent; read it again before signing",
                      "code": "sheet_changed"
                    }
                  },
                  "not_draft": {
                    "value": {
                      "error": "not draft: only a draft sheet is edited or signed",
                      "code": "not_draft"
                    }
                  },
                  "sheet_incomplete": {
                    "value": {
                      "error": "sheet incomplete: stages[1].kc (given in another stage)",
                      "code": "sheet_incomplete"
                    }
                  },
                  "sheet_expired": {
                    "value": {
                      "error": "sheet expired: its last valid day has passed",
                      "code": "sheet_expired"
                    }
                  },
                  "newer_version_signed": {
                    "value": {
                      "error": "newer version signed: a later version of this series is signed already",
                      "code": "newer_version_signed"
                    }
                  },
                  "unknown_statement_version": {
                    "value": {
                      "error": "unknown statement version: sign the current statement",
                      "code": "unknown_statement_version"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/agronomy-sheets/{id}/revoke": {
      "post": {
        "operationId": "revokeAgronomySheet",
        "summary": "Revoke a signed agronomic input sheet",
        "description": "#351. A signed or superseded sheet is revoked, with a reason, by an admin of the company or by the agronomist who signed it (another agronomist: 403 `not_signer`); final. Needs a recent password and second-factor proof (#87 step-up). Audited (`agronomy_sheet.revoke`: the series, version and reason). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AgronomySheetRevoke"
              },
              "example": {
                "reason": "Wrong province"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The revoked sheet.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheet"
                },
                "example": {
                  "id": 7,
                  "series_key": "durian:Ri6:82",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province_code": "82",
                  "version": 2,
                  "status": "revoked",
                  "valid_from": "2027-01-01",
                  "valid_to": "2027-06-30",
                  "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                  "created_by": "agronomist@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "agronomist@coop.example",
                  "updated_at": 1790000600.5,
                  "copied_from_id": null,
                  "supersedes_id": 4,
                  "superseded_by_id": null,
                  "signed_at": 1790007200.5,
                  "superseded_at": null,
                  "revoked_at": 1790010800.5,
                  "revoked_by": "admin@coop.example",
                  "revoke_reason": "Wrong province",
                  "body": {
                    "stages": [
                      {
                        "code": "flowering",
                        "name": {
                          "vi": "Ra hoa",
                          "en": "Flowering",
                          "zh-Hans": "开花期"
                        },
                        "start": "2027-01-01",
                        "end": "2027-02-15"
                      }
                    ],
                    "references": [
                      {
                        "title": "Agronomist's field notes, season 2027"
                      }
                    ]
                  },
                  "attestation": {
                    "id": 5,
                    "agronomist_id": 3,
                    "user_id": 41,
                    "legal_name": "Nguyễn Văn An",
                    "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
                    "statement_version": "1",
                    "statement_text_sha256": "9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "signed_at": 1790007200.5,
                    "second_factor_at": 1790007000.5
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or no reason, or a bad X-Request-Id. Or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: text of 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or the signing agronomist of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left); not signer.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  },
                  "not_signer": {
                    "value": {
                      "error": "not signer: only the agronomist who signed a sheet, or an admin of the company, revokes it",
                      "code": "not_signer"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sheet of this company: another company's answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The sheet is not signed or superseded. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_signed": {
                    "value": {
                      "error": "not signed: only a signed or superseded sheet is revoked",
                      "code": "not_signed"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/agronomy-sheets/{id}/copy": {
      "post": {
        "operationId": "copyAgronomySheet",
        "summary": "Copy a sheet into a new draft",
        "description": "#351. A new draft of the sheet's series with the series' next version, the sheet's validity and body: how a signed sheet gets a new version. Audited (`agronomy_sheet.copy`: the new sheet, its source, series and version). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "7"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "201": {
            "description": "The new draft.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "ETag": {
                "description": "The sheet's `body_sha256`, quoted: send it back in If-Match to edit the draft.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomySheet"
                },
                "example": {
                  "id": 7,
                  "series_key": "durian:Ri6:82",
                  "crop": "durian",
                  "variety": "Ri6",
                  "province_code": "82",
                  "version": 2,
                  "status": "draft",
                  "valid_from": "2027-01-01",
                  "valid_to": "2027-06-30",
                  "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                  "created_by": "agronomist@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "agronomist@coop.example",
                  "updated_at": 1790000600.5,
                  "copied_from_id": 6,
                  "supersedes_id": null,
                  "superseded_by_id": null,
                  "signed_at": null,
                  "superseded_at": null,
                  "revoked_at": null,
                  "revoked_by": null,
                  "revoke_reason": null,
                  "body": {
                    "stages": [
                      {
                        "code": "flowering",
                        "name": {
                          "vi": "Ra hoa",
                          "en": "Flowering",
                          "zh-Hans": "开花期"
                        },
                        "start": "2027-01-01",
                        "end": "2027-02-15"
                      }
                    ],
                    "references": [
                      {
                        "title": "Agronomist's field notes, season 2027"
                      }
                    ]
                  },
                  "attestation": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestIdOrIdempotencyKey"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or agronomist of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such sheet of this company: another company's answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 7",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyKeyConflict"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/agronomy/home": {
      "get": {
        "operationId": "getAgronomyHome",
        "summary": "Read the agronomist's home",
        "description": "#351. For an agronomist of the selected company: Now (the drafts waiting for a signature, oldest first), Today (today's control work: empty until wave 2 of #243, which the answer says) and Status (whether the caller can sign: registry status, two-step sign-in, step-up window; their signed sheets whose last valid day is within 30 days). Computed at most every 10 seconds per company and person (a draft just signed may be listed that long); the step-up window is the session's. `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an agronomist acts as a person (ADR 0014). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the agronomy console.",
        "tags": [
          "agronomy"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The home.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AgronomyHome"
                },
                "example": {
                  "generated_at": 1790007200.5,
                  "now": {
                    "drafts_waiting": 1,
                    "drafts": [
                      {
                        "id": 7,
                        "series_key": "durian:Ri6:82",
                        "crop": "durian",
                        "variety": "Ri6",
                        "province_code": "82",
                        "version": 2,
                        "status": "draft",
                        "valid_from": "2027-01-01",
                        "valid_to": "2027-06-30",
                        "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                        "created_at": 1790000000.5,
                        "updated_at": 1790000600.5,
                        "signed_at": null,
                        "superseded_at": null,
                        "revoked_at": null,
                        "signed_by": null
                      }
                    ]
                  },
                  "today": {
                    "state": "available",
                    "reason": "the programs composed today from sheets the caller signed, and the zones of their rules on fallback",
                    "programs": [
                      {
                        "id": 31,
                        "device_id": "irr-ph7-01",
                        "status": "proposed",
                        "proposed_at": 1790007300.5,
                        "sheets": [
                          {
                            "id": 7,
                            "version": 2,
                            "series_key": "durian:Ri6:82"
                          }
                        ]
                      }
                    ],
                    "fallback_zones": [
                      {
                        "rule_id": 12,
                        "rule_name": "Block A moisture",
                        "device_id": "irr-ph7-01",
                        "zones": [
                          1,
                          2
                        ],
                        "reason": "frozen"
                      }
                    ]
                  },
                  "status": {
                    "registry": "verified",
                    "two_factor": true,
                    "expiring_days": 30,
                    "expiring": [],
                    "step_up": {
                      "fresh": false,
                      "until": null
                    },
                    "can_sign": true
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (agronomist, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/zones": {
      "get": {
        "operationId": "listControlZones",
        "summary": "List the company's irrigation zones",
        "description": "#352. The zones of the company's irrigation controllers, by controller and zone number (an operator: the controllers of its facilities). Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only this controller's.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          }
        ],
        "responses": {
          "200": {
            "description": "The zones.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlZonePage"
                },
                "example": {
                  "items": [
                    {
                      "id": 4,
                      "device_id": "irr-ph7-01",
                      "zone": 3,
                      "growing_area": "VN-DL-SR-0123",
                      "name": "Block A, row 1-8",
                      "irrigated_area_m2": 2400.0,
                      "nominal_flow_lpm": 120.0,
                      "efficiency": 0.9,
                      "max_daily_l": 30000.0,
                      "probes": [
                        {
                          "device_id": "soil-ph7-03",
                          "depth_cm": 30.0
                        }
                      ],
                      "weather_station": null,
                      "controller_utc_offset": "+07:00",
                      "offset_ok": true,
                      "field_capacity_pct": null,
                      "wilting_point_pct": null,
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5,
                      "updated_by": "admin@coop.example",
                      "updated_at": 1790000000.5
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "A bad `device`. Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "device": {
                    "value": {
                      "error": "bad device: a device id",
                      "code": "bad_device"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor or operator of the company (an operator for its facilities' controllers), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createControlZone",
        "summary": "Create an irrigation zone",
        "description": "#352. A zone of an irrigation controller of the company (active, approved by CropPath, with a fixed placement in force) with its installation facts; the controller's rules are due again. Audited (`control_zone.create`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ControlZoneCreate"
              },
              "example": {
                "device_id": "irr-ph7-01",
                "zone": 3,
                "name": "Block A, row 1-8",
                "irrigated_area_m2": 2400.0,
                "nominal_flow_lpm": 120.0,
                "efficiency": 0.9,
                "max_daily_l": 30000.0,
                "probes": [
                  {
                    "device_id": "soil-ph7-03",
                    "depth_cm": 30.0
                  }
                ],
                "controller_utc_offset": "+07:00"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The zone.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlZone"
                },
                "example": {
                  "id": 4,
                  "device_id": "irr-ph7-01",
                  "zone": 3,
                  "growing_area": "VN-DL-SR-0123",
                  "name": "Block A, row 1-8",
                  "irrigated_area_m2": 2400.0,
                  "nominal_flow_lpm": 120.0,
                  "efficiency": 0.9,
                  "max_daily_l": 30000.0,
                  "probes": [
                    {
                      "device_id": "soil-ph7-03",
                      "depth_cm": 30.0
                    }
                  ],
                  "weather_station": null,
                  "controller_utc_offset": "+07:00",
                  "offset_ok": true,
                  "field_capacity_pct": null,
                  "wilting_point_pct": null,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown or missing field or a value out of its bounds, field capacity and wilting point not given together with the wilting point below it, or a probe whose profile does not produce soil.moisture (`probe_not_moisture`, #365). Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "efficiency": {
                    "value": {
                      "error": "invalid efficiency: from 0.3 to 1",
                      "code": "invalid_efficiency"
                    }
                  },
                  "water_holding": {
                    "value": {
                      "error": "invalid water holding: field_capacity_pct and wilting_point_pct are given together, the wilting point below field capacity",
                      "code": "invalid_water_holding"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "probe_not_moisture": {
                    "value": {
                      "error": "probe not moisture: probes[0] is not a soil moisture probe",
                      "code": "probe_not_moisture"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "Not an irrigation controller of the company, not approved, not placed, or the zone exists. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_placed": {
                    "value": {
                      "error": "controller not placed: the controller has no fixed placement in a growing area in force",
                      "code": "controller_not_placed"
                    }
                  },
                  "zone_exists": {
                    "value": {
                      "error": "zone exists: this controller already has this zone",
                      "code": "zone_exists"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/zones/{device}/{zone}": {
      "put": {
        "operationId": "updateControlZone",
        "summary": "Edit an irrigation zone",
        "description": "#352. Each member given replaces it; the growing area is read again from the controller's placement and the controller's rules are due again. Audited (`control_zone.update`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "path",
            "required": true,
            "description": "The irrigation controller's device id.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "name": "zone",
            "in": "path",
            "required": true,
            "description": "The zone number, 1 to 16.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]?$"
            },
            "example": "3"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ControlZoneUpdate"
              },
              "example": {
                "name": "Block A, row 1-8",
                "max_daily_l": 30000
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The zone.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlZone"
                },
                "example": {
                  "id": 4,
                  "device_id": "irr-ph7-01",
                  "zone": 3,
                  "growing_area": "VN-DL-SR-0123",
                  "name": "Block A, row 1-8",
                  "irrigated_area_m2": 2400.0,
                  "nominal_flow_lpm": 120.0,
                  "efficiency": 0.9,
                  "max_daily_l": 30000.0,
                  "probes": [
                    {
                      "device_id": "soil-ph7-03",
                      "depth_cm": 30.0
                    }
                  ],
                  "weather_station": null,
                  "controller_utc_offset": "+07:00",
                  "offset_ok": true,
                  "field_capacity_pct": null,
                  "wilting_point_pct": null,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a value out of its bounds, field capacity and wilting point not given together with the wilting point below it, or a probe whose profile does not produce soil.moisture (`probe_not_moisture`, #365). Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "probes": {
                    "value": {
                      "error": "invalid probes: a list of at most 16",
                      "code": "invalid_probes"
                    }
                  },
                  "water_holding": {
                    "value": {
                      "error": "invalid water holding: field_capacity_pct and wilting_point_pct are given together, the wilting point below field capacity",
                      "code": "invalid_water_holding"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "probe_not_moisture": {
                    "value": {
                      "error": "probe not moisture: probes[0] is not a soil moisture probe",
                      "code": "probe_not_moisture"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such zone of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: irr-ph7-01/3",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The controller is no longer approved or placed. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_approved": {
                    "value": {
                      "error": "controller not approved: the controller is not active and approved by CropPath",
                      "code": "controller_not_approved"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      },
      "delete": {
        "operationId": "deleteControlZone",
        "summary": "Delete an irrigation zone",
        "description": "#352. A zone no enabled rule waters. Audited (`control_zone.delete`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "path",
            "required": true,
            "description": "The irrigation controller's device id.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "name": "zone",
            "in": "path",
            "required": true,
            "description": "The zone number, 1 to 16.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]?$"
            },
            "example": "3"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The zone as it was.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlZone"
                },
                "example": {
                  "id": 4,
                  "device_id": "irr-ph7-01",
                  "zone": 3,
                  "growing_area": "VN-DL-SR-0123",
                  "name": "Block A, row 1-8",
                  "irrigated_area_m2": 2400.0,
                  "nominal_flow_lpm": 120.0,
                  "efficiency": 0.9,
                  "max_daily_l": 30000.0,
                  "probes": [
                    {
                      "device_id": "soil-ph7-03",
                      "depth_cm": 30.0
                    }
                  ],
                  "weather_station": null,
                  "controller_utc_offset": "+07:00",
                  "offset_ok": true,
                  "field_capacity_pct": null,
                  "wilting_point_pct": null,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5
                }
              }
            }
          },
          "400": {
            "description": "A bad request. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such zone of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: irr-ph7-01/3",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "An enabled rule waters the zone. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "zone_in_use": {
                    "value": {
                      "error": "zone in use: an enabled rule waters this zone; disable it first",
                      "code": "zone_in_use"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/rules": {
      "get": {
        "operationId": "listControlRules",
        "summary": "List the company's irrigation rules",
        "description": "#352. Newest first, by controller and state (an operator: its facilities' controllers; an agronomist: the rules bound to a sheet they signed). Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only this controller's.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "name": "state",
            "in": "query",
            "required": false,
            "description": "Only rules in this state.",
            "schema": {
              "type": "string",
              "enum": [
                "disabled",
                "ok",
                "blocked",
                "fallback"
              ]
            },
            "example": "blocked"
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "description": "Only rows with a smaller id: the previous page's `next_before`.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "41"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "At most this many items (1 to 200; 100 by default).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "A page of rules.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRulePage"
                },
                "example": {
                  "items": [
                    {
                      "id": 12,
                      "kind": "schedule",
                      "name": "Block A schedule",
                      "device_id": "irr-ph7-01",
                      "zones": [
                        3
                      ],
                      "sheet_id": 7,
                      "windows": [
                        {
                          "start_local": "05:30",
                          "max_duration_s": 7200
                        }
                      ],
                      "fallback_rule_id": null,
                      "approval": "required",
                      "eval_interval_s": 900,
                      "min_interval_s": 300,
                      "peer_tolerance_pct": null,
                      "min_probes": null,
                      "enabled": true,
                      "state": "ok",
                      "state_reason": null,
                      "state_at": 1790007300.5,
                      "next_run_at": 1790035500.0,
                      "last_run_at": 1790007300.5,
                      "created_by": "admin@coop.example",
                      "created_at": 1790000000.5,
                      "updated_by": "admin@coop.example",
                      "updated_at": 1790000000.5,
                      "enabled_by": "admin@coop.example",
                      "enabled_at": 1790007200.5,
                      "auto_approval_by": null,
                      "auto_approval_at": null,
                      "hold_until": null,
                      "sheet": {
                        "id": 7,
                        "series_key": "durian:Ri6:82",
                        "version": 2,
                        "status": "signed",
                        "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                        "valid_from": "2027-01-01",
                        "valid_to": "2027-06-30"
                      },
                      "sheet_gate": null,
                      "resumed_command_id": null
                    }
                  ],
                  "next_before": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `device`, `state`, `before` or `limit`. Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "state": {
                    "value": {
                      "error": "invalid state: one of disabled, ok, blocked, fallback",
                      "code": "invalid_state"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "operationId": "createControlRule",
        "summary": "Create an irrigation rule",
        "description": "#352. A disabled rule: a schedule, threshold or et0_budget rule (#353; lighting is recorded but cannot be enabled yet) of one controller's zones, bound to a signed sheet of the company, with its windows. Approval is `required`. Audited (`control_rule.create`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ControlRuleCreate"
              },
              "example": {
                "kind": "schedule",
                "name": "Block A schedule",
                "device_id": "irr-ph7-01",
                "zones": [
                  3
                ],
                "sheet_id": 7,
                "windows": [
                  {
                    "start_local": "05:30",
                    "max_duration_s": 7200
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The rule.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRule"
                },
                "example": {
                  "id": 12,
                  "kind": "schedule",
                  "name": "Block A schedule",
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "sheet_id": 7,
                  "windows": [
                    {
                      "start_local": "05:30",
                      "max_duration_s": 7200
                    }
                  ],
                  "fallback_rule_id": null,
                  "approval": "required",
                  "eval_interval_s": 900,
                  "min_interval_s": 300,
                  "peer_tolerance_pct": null,
                  "min_probes": null,
                  "enabled": false,
                  "state": "disabled",
                  "state_reason": null,
                  "state_at": null,
                  "next_run_at": null,
                  "last_run_at": null,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5,
                  "enabled_by": null,
                  "enabled_at": null,
                  "auto_approval_by": null,
                  "auto_approval_at": null,
                  "hold_until": null,
                  "sheet": {
                    "id": 7,
                    "series_key": "durian:Ri6:82",
                    "version": 2,
                    "status": "signed",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "valid_from": "2027-01-01",
                    "valid_to": "2027-06-30"
                  },
                  "sheet_gate": null,
                  "resumed_command_id": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown or missing field, a bad window or zone list, a fallback that is not a schedule rule of the same controller and zones. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "windows": {
                    "value": {
                      "error": "invalid windows: two windows overlap",
                      "code": "invalid_windows"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "409": {
            "description": "The sheet is not a signed sheet of the company. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "sheet_not_signed": {
                    "value": {
                      "error": "sheet not signed: a rule binds a signed sheet of the company",
                      "code": "sheet_not_signed"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/rules/{id}": {
      "get": {
        "operationId": "getControlRule",
        "summary": "Read an irrigation rule",
        "description": "#352. One rule with its bound sheet and its state. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          }
        ],
        "responses": {
          "200": {
            "description": "The rule.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRule"
                },
                "example": {
                  "id": 12,
                  "kind": "schedule",
                  "name": "Block A schedule",
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "sheet_id": 7,
                  "windows": [
                    {
                      "start_local": "05:30",
                      "max_duration_s": 7200
                    }
                  ],
                  "fallback_rule_id": null,
                  "approval": "required",
                  "eval_interval_s": 900,
                  "min_interval_s": 300,
                  "peer_tolerance_pct": null,
                  "min_probes": null,
                  "enabled": true,
                  "state": "ok",
                  "state_reason": null,
                  "state_at": 1790007300.5,
                  "next_run_at": 1790035500.0,
                  "last_run_at": 1790007300.5,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5,
                  "enabled_by": "admin@coop.example",
                  "enabled_at": 1790007200.5,
                  "auto_approval_by": null,
                  "auto_approval_at": null,
                  "hold_until": null,
                  "sheet": {
                    "id": 7,
                    "series_key": "durian:Ri6:82",
                    "version": 2,
                    "status": "signed",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "valid_from": "2027-01-01",
                    "valid_to": "2027-06-30"
                  },
                  "sheet_gate": null,
                  "resumed_command_id": null
                }
              }
            }
          },
          "400": {
            "description": "A bad request. Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such rule of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "put": {
        "operationId": "updateControlRule",
        "summary": "Edit a disabled irrigation rule",
        "description": "#352. Each member given replaces it; an enabled rule, or the fallback of an enabled threshold rule, is never edited (409). Audited (`control_rule.update`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ControlRuleUpdate"
              },
              "example": {
                "sheet_id": 9
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The rule.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRule"
                },
                "example": {
                  "id": 12,
                  "kind": "schedule",
                  "name": "Block A schedule",
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "sheet_id": 7,
                  "windows": [
                    {
                      "start_local": "05:30",
                      "max_duration_s": 7200
                    }
                  ],
                  "fallback_rule_id": null,
                  "approval": "required",
                  "eval_interval_s": 900,
                  "min_interval_s": 300,
                  "peer_tolerance_pct": null,
                  "min_probes": null,
                  "enabled": false,
                  "state": "disabled",
                  "state_reason": null,
                  "state_at": null,
                  "next_run_at": null,
                  "last_run_at": null,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5,
                  "enabled_by": null,
                  "enabled_at": null,
                  "auto_approval_by": null,
                  "auto_approval_at": null,
                  "hold_until": null,
                  "sheet": {
                    "id": 7,
                    "series_key": "durian:Ri6:82",
                    "version": 2,
                    "status": "signed",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "valid_from": "2027-01-01",
                    "valid_to": "2027-06-30"
                  },
                  "sheet_gate": null,
                  "resumed_command_id": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a value out of its bounds. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "zones": {
                    "value": {
                      "error": "invalid zones: a zone given twice",
                      "code": "invalid_zones"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such rule of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The rule is enabled, it is the fallback of an enabled rule, or the sheet is not signed. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "rule_enabled": {
                    "value": {
                      "error": "rule enabled: disable the rule before changing it",
                      "code": "rule_enabled"
                    }
                  },
                  "fallback_in_use": {
                    "value": {
                      "error": "fallback in use: an enabled threshold or et0_budget rule falls back to this rule",
                      "code": "fallback_in_use"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/rules/{id}/enable": {
      "post": {
        "operationId": "enableControlRule",
        "summary": "Enable an irrigation rule",
        "description": "#352. Checks the controller, the zones, the bound sheet (signed, valid today, its hash intact, its signer verified, its crop the zones' crop, complete for the kind), a threshold rule's fallback and gate parameters, an et0_budget rule's fallback, its gate parameters given together and a weather station on every zone (#353), and that no other enabled rule of the controller waters one of its zones; the rule is then due at once. Needs a recent second-factor proof. Audited (`control_rule.enable`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The rule.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRule"
                },
                "example": {
                  "id": 12,
                  "kind": "schedule",
                  "name": "Block A schedule",
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "sheet_id": 7,
                  "windows": [
                    {
                      "start_local": "05:30",
                      "max_duration_s": 7200
                    }
                  ],
                  "fallback_rule_id": null,
                  "approval": "required",
                  "eval_interval_s": 900,
                  "min_interval_s": 300,
                  "peer_tolerance_pct": null,
                  "min_probes": null,
                  "enabled": true,
                  "state": "ok",
                  "state_reason": null,
                  "state_at": 1790007300.5,
                  "next_run_at": 1790035500.0,
                  "last_run_at": 1790007300.5,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5,
                  "enabled_by": "admin@coop.example",
                  "enabled_at": 1790007200.5,
                  "auto_approval_by": null,
                  "auto_approval_at": null,
                  "hold_until": null,
                  "sheet": {
                    "id": 7,
                    "series_key": "durian:Ri6:82",
                    "version": 2,
                    "status": "signed",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "valid_from": "2027-01-01",
                    "valid_to": "2027-06-30"
                  },
                  "sheet_gate": null,
                  "resumed_command_id": null
                }
              }
            }
          },
          "400": {
            "description": "A bad request. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such rule of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The rule cannot be enabled now: the message says why (`kind_not_available`: a lighting rule). Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "sheet_not_usable": {
                    "value": {
                      "error": "sheet not usable: sheet_expired",
                      "code": "sheet_not_usable"
                    }
                  },
                  "zone_taken": {
                    "value": {
                      "error": "zone taken: another enabled rule of the controller waters one of these zones",
                      "code": "zone_taken"
                    }
                  },
                  "kind_not_available": {
                    "value": {
                      "error": "kind not available: this kind of rule cannot be enabled yet",
                      "code": "kind_not_available"
                    }
                  },
                  "station_missing": {
                    "value": {
                      "error": "station missing: every zone of an et0_budget rule needs a weather station",
                      "code": "station_missing"
                    }
                  },
                  "gate_parameters_incomplete": {
                    "value": {
                      "error": "gate parameters incomplete: an et0_budget rule takes peer_tolerance_pct and min_probes together",
                      "code": "gate_parameters_incomplete"
                    }
                  },
                  "already_enabled": {
                    "value": {
                      "error": "already enabled: the rule is enabled",
                      "code": "already_enabled"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/rules/{id}/disable": {
      "post": {
        "operationId": "disableControlRule",
        "summary": "Disable an irrigation rule",
        "description": "#352. At once: the controller's other rules are due again, and a dispatched program still holding steps of the rule's zones to come is withdrawn (the #242 durable withdrawal). No step-up: disabling only stops water. Audited (`control_rule.disable`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The rule.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRule"
                },
                "example": {
                  "id": 12,
                  "kind": "schedule",
                  "name": "Block A schedule",
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "sheet_id": 7,
                  "windows": [
                    {
                      "start_local": "05:30",
                      "max_duration_s": 7200
                    }
                  ],
                  "fallback_rule_id": null,
                  "approval": "required",
                  "eval_interval_s": 900,
                  "min_interval_s": 300,
                  "peer_tolerance_pct": null,
                  "min_probes": null,
                  "enabled": false,
                  "state": "disabled",
                  "state_reason": null,
                  "state_at": null,
                  "next_run_at": null,
                  "last_run_at": null,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5,
                  "enabled_by": null,
                  "enabled_at": null,
                  "auto_approval_by": null,
                  "auto_approval_at": null,
                  "hold_until": null,
                  "sheet": {
                    "id": 7,
                    "series_key": "durian:Ri6:82",
                    "version": 2,
                    "status": "signed",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "valid_from": "2027-01-01",
                    "valid_to": "2027-06-30"
                  },
                  "sheet_gate": null,
                  "resumed_command_id": null
                }
              }
            }
          },
          "400": {
            "description": "A bad request. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such rule of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The rule is not enabled. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_enabled": {
                    "value": {
                      "error": "not enabled: the rule is disabled",
                      "code": "not_enabled"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/rules/{id}/approval": {
      "post": {
        "operationId": "setControlRuleApproval",
        "summary": "Set an irrigation rule's approval",
        "description": "#352. `required` (every program waits for a person) or `auto`, only once programs of the controller were approved by a person on at least 7 local days since the rule was created. Needs a recent second-factor proof. Audited (`control_rule.auto_approval`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ControlRuleApproval"
              },
              "example": {
                "approval": "auto"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The rule.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRule"
                },
                "example": {
                  "id": 12,
                  "kind": "schedule",
                  "name": "Block A schedule",
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "sheet_id": 7,
                  "windows": [
                    {
                      "start_local": "05:30",
                      "max_duration_s": 7200
                    }
                  ],
                  "fallback_rule_id": null,
                  "approval": "auto",
                  "eval_interval_s": 900,
                  "min_interval_s": 300,
                  "peer_tolerance_pct": null,
                  "min_probes": null,
                  "enabled": true,
                  "state": "ok",
                  "state_reason": null,
                  "state_at": 1790007300.5,
                  "next_run_at": 1790035500.0,
                  "last_run_at": 1790007300.5,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5,
                  "enabled_by": "admin@coop.example",
                  "enabled_at": 1790007200.5,
                  "auto_approval_by": "admin@coop.example",
                  "auto_approval_at": 1790700000.5,
                  "hold_until": null,
                  "sheet": {
                    "id": 7,
                    "series_key": "durian:Ri6:82",
                    "version": 2,
                    "status": "signed",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "valid_from": "2027-01-01",
                    "valid_to": "2027-06-30"
                  },
                  "sheet_gate": null,
                  "resumed_command_id": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON or an approval other than required or auto. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "approval": {
                    "value": {
                      "error": "invalid approval: required or auto",
                      "code": "invalid_approval"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such rule of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Not enough approved days yet. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "approval_history_short": {
                    "value": {
                      "error": "approval history short: programs of this controller need a person's approval on at least 7 days first",
                      "code": "approval_history_short"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/rules/{id}/preview": {
      "get": {
        "operationId": "previewControlRule",
        "summary": "Preview an irrigation rule",
        "description": "#352. A dry run of the rule's controller as if the rule were enabled (in place of the enabled rules sharing a zone with it): every zone's decision, the health gate's decisions, the sheets cited and the set_program params a program issued now would carry. Writes and sends nothing. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          }
        ],
        "responses": {
          "200": {
            "description": "The preview.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlPreview"
                },
                "example": {
                  "generated_at": 1790007300.5,
                  "rule_id": 12,
                  "device_id": "irr-ph7-01",
                  "provenance": {
                    "local_date": "2027-03-02",
                    "composed_at": 1790007300.5,
                    "approval": "required",
                    "error": null,
                    "rules": [
                      {
                        "id": 12,
                        "kind": "schedule",
                        "state": "ok",
                        "applied": "schedule",
                        "zones": [
                          3
                        ]
                      }
                    ],
                    "sheets": [
                      {
                        "id": 7,
                        "series_key": "durian:Ri6:82",
                        "version": 2,
                        "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                        "attestation_id": 5,
                        "signed_at": 1790000600.5,
                        "valid_from": "2027-01-01",
                        "valid_to": "2027-06-30"
                      }
                    ],
                    "zones": [
                      {
                        "zone": 3,
                        "rule_id": 12,
                        "mode": "schedule",
                        "litres": 216.0,
                        "clamps": []
                      }
                    ],
                    "plan": [
                      {
                        "zone": 3,
                        "start_s": 19800,
                        "duration_s": 1800,
                        "max_volume_l": 270
                      }
                    ],
                    "signature": "{...}",
                    "replaces_program_id": null,
                    "withdrew": false
                  },
                  "gate": [],
                  "params": {
                    "program": {
                      "steps": [
                        {
                          "zone": 3,
                          "start_s": 19800,
                          "duration_s": 1800,
                          "max_volume_l": 270
                        }
                      ]
                    },
                    "valid_until_s": 45899
                  },
                  "blocked_zones": []
                }
              }
            }
          },
          "400": {
            "description": "A bad request. Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such rule of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/programs": {
      "get": {
        "operationId": "listControlPrograms",
        "summary": "List the company's irrigation programs",
        "description": "#352. Newest first, by controller, status and local dates (an operator: its facilities' controllers; an agronomist: the programs citing a sheet they signed). Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only this controller's.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "description": "Only programs in this status.",
            "schema": {
              "type": "string",
              "enum": [
                "proposed",
                "approved",
                "rejected",
                "dispatched",
                "superseded",
                "failed",
                "blocked",
                "expired",
                "withdrawn"
              ]
            },
            "example": "proposed"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Only programs of this local date (Asia/Ho_Chi_Minh) or later.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-01"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "Only programs of this local date or earlier.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-31"
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "description": "Only rows with a smaller id: the previous page's `next_before`.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "41"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "At most this many items (1 to 200; 50 by default).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "A page of programs.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlProgramPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 31,
                      "device_id": "irr-ph7-01",
                      "local_date": "2027-03-02",
                      "status": "proposed",
                      "cause": "daily",
                      "proposed_at": 1790007300.5,
                      "expires_at": 1790053200.0,
                      "decided_by": null,
                      "decided_at": null,
                      "dispatched_at": null,
                      "command_id": null,
                      "program_version": null,
                      "error": null,
                      "steps": 1,
                      "litres": 216.0,
                      "rules": [
                        {
                          "id": 12,
                          "kind": "schedule",
                          "state": "ok",
                          "applied": "schedule"
                        }
                      ],
                      "sheets": [
                        {
                          "id": 7,
                          "version": 2,
                          "series_key": "durian:Ri6:82",
                          "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e"
                        }
                      ],
                      "withdrew": false
                    }
                  ],
                  "next_before": null
                }
              }
            }
          },
          "400": {
            "description": "A bad `device`, `status`, `from`, `to`, `before` or `limit`. Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "status": {
                    "value": {
                      "error": "invalid status: one of proposed, approved, rejected, dispatched, superseded, failed, blocked, expired",
                      "code": "invalid_status"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/programs/{id}": {
      "get": {
        "operationId": "getControlProgram",
        "summary": "Read an irrigation program",
        "description": "#352. One program with its params, provenance (rules, sheets cited with version and SHA-256, zone decisions, the planned budget per zone and the ET0 days cited), gate decisions and the #242 command's state and replies. To an agronomist the command's `issued_by` and the replies' bodies are null. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          }
        ],
        "responses": {
          "200": {
            "description": "The program.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlProgram"
                },
                "example": {
                  "id": 31,
                  "device_id": "irr-ph7-01",
                  "local_date": "2027-03-02",
                  "status": "dispatched",
                  "cause": "daily",
                  "proposed_at": 1790007300.5,
                  "expires_at": 1790053200.0,
                  "decided_by": "op@coop.example",
                  "decided_at": 1790010000.5,
                  "dispatched_at": 1790010000.5,
                  "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                  "program_version": 18,
                  "error": null,
                  "steps": 1,
                  "litres": 216.0,
                  "rules": [
                    {
                      "id": 12,
                      "kind": "schedule",
                      "state": "ok",
                      "applied": "schedule"
                    }
                  ],
                  "sheets": [
                    {
                      "id": 7,
                      "version": 2,
                      "series_key": "durian:Ri6:82",
                      "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e"
                    }
                  ],
                  "withdrew": false,
                  "params": {
                    "program": {
                      "steps": [
                        {
                          "zone": 3,
                          "start_s": 19800,
                          "duration_s": 1800,
                          "max_volume_l": 270
                        }
                      ]
                    },
                    "program_version": 18,
                    "valid_until_s": 43199
                  },
                  "provenance": {
                    "local_date": "2027-03-02",
                    "composed_at": 1790007300.5,
                    "approval": "required",
                    "error": null,
                    "rules": [
                      {
                        "id": 12,
                        "kind": "schedule",
                        "state": "ok",
                        "applied": "schedule",
                        "zones": [
                          3
                        ]
                      }
                    ],
                    "sheets": [
                      {
                        "id": 7,
                        "series_key": "durian:Ri6:82",
                        "version": 2,
                        "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                        "attestation_id": 5,
                        "signed_at": 1790000600.5,
                        "valid_from": "2027-01-01",
                        "valid_to": "2027-06-30"
                      }
                    ],
                    "zones": [
                      {
                        "zone": 3,
                        "rule_id": 12,
                        "mode": "schedule",
                        "litres": 216.0,
                        "clamps": []
                      }
                    ],
                    "plan": [
                      {
                        "zone": 3,
                        "start_s": 19800,
                        "duration_s": 1800,
                        "max_volume_l": 270
                      }
                    ],
                    "signature": "{...}",
                    "replaces_program_id": null,
                    "withdrew": false
                  },
                  "decision_note": null,
                  "withdrawal": null,
                  "gate_decisions": [],
                  "command": {
                    "id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                    "status": "accepted",
                    "reason": null,
                    "issued_by": "op@coop.example",
                    "issued_at": 1790010000.5,
                    "accepted_at": 1790010002.5,
                    "completed_at": null,
                    "expires_at": 1790053199.0,
                    "result": {
                      "state": "accepted"
                    },
                    "replies": [
                      {
                        "received_at": 1790010002.5,
                        "applied": true,
                        "body": {
                          "state": "accepted"
                        }
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad request. Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such program of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 31",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/programs/{id}/approve": {
      "post": {
        "operationId": "approveControlProgram",
        "summary": "Approve and dispatch a proposed program",
        "description": "#352. Composes the controller again now (sheet gate, controller, health gate): when a decision changed since the proposal, the proposal is superseded by a new one and the approval answers 409 `program_changed` naming it; while a person's own set_program is in force on the controller and its rules were not resumed over it (the engine's manual override), the proposal is superseded and the approval answers 409 `manual_override_active`: an admin resumes the rules first; otherwise the program is approved by the caller and dispatched at once through the #242 command channel, with only its steps still to come (CropPath signs it and assigns its program version). Approving opens valves: it needs a recent second-factor proof, as enabling a rule does. Audited (`control_program.approve`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false
              },
              "example": {}
            }
          }
        },
        "responses": {
          "200": {
            "description": "The program after its dispatch (`dispatched`, or `failed` with its error).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlProgram"
                },
                "example": {
                  "id": 31,
                  "device_id": "irr-ph7-01",
                  "local_date": "2027-03-02",
                  "status": "dispatched",
                  "cause": "daily",
                  "proposed_at": 1790007300.5,
                  "expires_at": 1790053200.0,
                  "decided_by": "op@coop.example",
                  "decided_at": 1790010000.5,
                  "dispatched_at": 1790010000.5,
                  "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                  "program_version": 18,
                  "error": null,
                  "steps": 1,
                  "litres": 216.0,
                  "rules": [
                    {
                      "id": 12,
                      "kind": "schedule",
                      "state": "ok",
                      "applied": "schedule"
                    }
                  ],
                  "sheets": [
                    {
                      "id": 7,
                      "version": 2,
                      "series_key": "durian:Ri6:82",
                      "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e"
                    }
                  ],
                  "withdrew": false,
                  "params": {
                    "program": {
                      "steps": [
                        {
                          "zone": 3,
                          "start_s": 19800,
                          "duration_s": 1800,
                          "max_volume_l": 270
                        }
                      ]
                    },
                    "program_version": 18,
                    "valid_until_s": 43199
                  },
                  "provenance": {
                    "local_date": "2027-03-02",
                    "composed_at": 1790007300.5,
                    "approval": "required",
                    "error": null,
                    "rules": [
                      {
                        "id": 12,
                        "kind": "schedule",
                        "state": "ok",
                        "applied": "schedule",
                        "zones": [
                          3
                        ]
                      }
                    ],
                    "sheets": [
                      {
                        "id": 7,
                        "series_key": "durian:Ri6:82",
                        "version": 2,
                        "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                        "attestation_id": 5,
                        "signed_at": 1790000600.5,
                        "valid_from": "2027-01-01",
                        "valid_to": "2027-06-30"
                      }
                    ],
                    "zones": [
                      {
                        "zone": 3,
                        "rule_id": 12,
                        "mode": "schedule",
                        "litres": 216.0,
                        "clamps": []
                      }
                    ],
                    "plan": [
                      {
                        "zone": 3,
                        "start_s": 19800,
                        "duration_s": 1800,
                        "max_volume_l": 270
                      }
                    ],
                    "signature": "{...}",
                    "replaces_program_id": null,
                    "withdrew": false
                  },
                  "decision_note": null,
                  "withdrawal": null,
                  "gate_decisions": [],
                  "command": {
                    "id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                    "status": "accepted",
                    "reason": null,
                    "issued_by": "op@coop.example",
                    "issued_at": 1790010000.5,
                    "accepted_at": 1790010002.5,
                    "completed_at": null,
                    "expires_at": 1790053199.0,
                    "result": {
                      "state": "accepted"
                    },
                    "replies": [
                      {
                        "received_at": 1790010002.5,
                        "applied": true,
                        "body": {
                          "state": "accepted"
                        }
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON or a body that is not empty. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, platform_admin acting for it, or an operator for the controllers of its facilities, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such program of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 31",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The program is not proposed, its day is over, its decisions changed, or a person's own program is in force on the controller. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_proposed": {
                    "value": {
                      "error": "not proposed: only a proposed program is approved or rejected",
                      "code": "not_proposed"
                    }
                  },
                  "program_expired": {
                    "value": {
                      "error": "program expired: its day is over",
                      "code": "program_expired"
                    }
                  },
                  "program_changed": {
                    "value": {
                      "error": "program changed: decisions changed since it was proposed; see program 32",
                      "code": "program_changed"
                    }
                  },
                  "manual_override_active": {
                    "value": {
                      "error": "manual override active: a person's own program is in force on the controller; resume its rules before approving",
                      "code": "manual_override_active"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/programs/{id}/reject": {
      "post": {
        "operationId": "rejectControlProgram",
        "summary": "Reject a proposed program",
        "description": "#352. With an optional reason; the engine proposes the same decisions again only once something changes. Audited (`control_program.reject`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ControlProgramReject"
              },
              "example": {
                "reason": "Rain expected this morning"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The program.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlProgram"
                },
                "example": {
                  "id": 31,
                  "device_id": "irr-ph7-01",
                  "local_date": "2027-03-02",
                  "status": "rejected",
                  "cause": "daily",
                  "proposed_at": 1790007300.5,
                  "expires_at": 1790053200.0,
                  "decided_by": "op@coop.example",
                  "decided_at": 1790010000.5,
                  "dispatched_at": null,
                  "command_id": null,
                  "program_version": null,
                  "error": null,
                  "steps": 1,
                  "litres": 216.0,
                  "rules": [
                    {
                      "id": 12,
                      "kind": "schedule",
                      "state": "ok",
                      "applied": "schedule"
                    }
                  ],
                  "sheets": [
                    {
                      "id": 7,
                      "version": 2,
                      "series_key": "durian:Ri6:82",
                      "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e"
                    }
                  ],
                  "withdrew": false,
                  "params": {
                    "program": {
                      "steps": [
                        {
                          "zone": 3,
                          "start_s": 19800,
                          "duration_s": 1800,
                          "max_volume_l": 270
                        }
                      ]
                    },
                    "valid_until_s": 45899
                  },
                  "provenance": {
                    "local_date": "2027-03-02",
                    "composed_at": 1790007300.5,
                    "approval": "required",
                    "error": null,
                    "rules": [
                      {
                        "id": 12,
                        "kind": "schedule",
                        "state": "ok",
                        "applied": "schedule",
                        "zones": [
                          3
                        ]
                      }
                    ],
                    "sheets": [
                      {
                        "id": 7,
                        "series_key": "durian:Ri6:82",
                        "version": 2,
                        "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                        "attestation_id": 5,
                        "signed_at": 1790000600.5,
                        "valid_from": "2027-01-01",
                        "valid_to": "2027-06-30"
                      }
                    ],
                    "zones": [
                      {
                        "zone": 3,
                        "rule_id": 12,
                        "mode": "schedule",
                        "litres": 216.0,
                        "clamps": []
                      }
                    ],
                    "plan": [
                      {
                        "zone": 3,
                        "start_s": 19800,
                        "duration_s": 1800,
                        "max_volume_l": 270
                      }
                    ],
                    "signature": "{...}",
                    "replaces_program_id": null,
                    "withdrew": false
                  },
                  "decision_note": "Rain expected this morning",
                  "withdrawal": null,
                  "gate_decisions": [],
                  "command": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field or a bad reason. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "invalid reason: text of 1 to 500 characters, without control characters",
                      "code": "invalid_reason"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, platform_admin acting for it, or an operator for the controllers of its facilities, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such program of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 31",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The program is not proposed. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_proposed": {
                    "value": {
                      "error": "not proposed: only a proposed program is approved or rejected",
                      "code": "not_proposed"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/devices/{id}/program-withdrawal": {
      "post": {
        "operationId": "withdrawDeviceProgram",
        "summary": "Withdraw the program a controller holds today",
        "description": "#367 (ADR 0016). Withdraws the program the controller holds now through the durable withdrawal of the command channel (the empty retained program, re-sent until acknowledged), never a new command: the controller stops the program and its running step (its final reply `aborted: cancelled`); a run started by hand keeps running to its own limit. In the same transaction the control program becomes `withdrawn` (who, when and why), programs composed before the stop that never went out (proposed or approved) are superseded, and the engine holds the controller until the next farm-local midnight (`hold_until`): it proposes and sends nothing automatic before then, while a person may still approve a program by hand. The answer never waits for the broker or the controller; the controller's reports say the program stopped. A reason is required; no step-up (a withdrawal only stops equipment). Audited (`device.program.withdraw`, with the reason). Through a signed-in session only: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The controller's device id.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProgramWithdrawalRequest"
              },
              "example": {
                "reason": "Rain since dawn, the beds are wet",
                "control_program_id": 31
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "The withdrawal is owed (and sent when the transport is up); the program is withdrawn and the engine holds the controller.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProgramWithdrawal"
                },
                "example": {
                  "withdrawal": {
                    "owed_at": "2027-03-02T07:35:00Z",
                    "published": true
                  },
                  "control_program": {
                    "id": 31,
                    "status": "withdrawn",
                    "program_version": 18
                  },
                  "hold_until": "2027-03-02T17:00:00Z"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, a missing or bad reason, a bad control_program_id or an unknown field. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "invalid_reason": {
                    "value": {
                      "error": "invalid reason: required, text of 1 to 500 characters",
                      "code": "invalid_reason"
                    }
                  },
                  "unknown_field": {
                    "value": {
                      "error": "unknown field: zone",
                      "code": "unknown_field"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, platform_admin acting for it, or an operator for the controllers of its facilities, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device of this company, or one outside the operator's facilities (both answer exactly like a missing one); or a control_program_id that is not one of the device's programs.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: irr-ph7-01",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "Nothing to stop, supersede or hold: the controller holds no program now, none is waiting to be sent, and it has no rule (or it cannot hold a program). Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "no_program": {
                    "value": {
                      "error": "no program: the controller holds no program, none is waiting to be sent and it has no rule",
                      "code": "no_program"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/devices/{id}/program-hold/release": {
      "post": {
        "operationId": "releaseDeviceProgramHold",
        "summary": "Release a controller's hold before its end",
        "description": "#367 (ADR 0016). Ends the hold a withdrawal put on the controller before the next farm-local midnight and makes its enabled rules due, so the control engine composes the controller again on its next run: under required approval that compose is a proposal a person approves as usual; under automatic approval it may send water, hence the recent second-factor proof (step-up). Nothing is sent by this operation. Audited (`device.program.hold_release`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403). Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The controller's device id.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false
              },
              "example": {}
            }
          }
        },
        "responses": {
          "200": {
            "description": "The hold is released and the controller's enabled rules are due.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProgramHoldRelease"
                },
                "example": {
                  "released": {
                    "hold_until": "2027-03-02T17:00:00Z",
                    "released_at": "2027-03-02T09:10:00Z"
                  },
                  "rules_due": 1
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON or a body that is not an empty object. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  },
                  "not_empty": {
                    "value": {
                      "error": "expected an empty JSON object",
                      "code": "expected_an_empty_json_object"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, platform_admin acting for it, or an operator for the controllers of its facilities, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such device of this company, or one outside the operator's facilities (both answer exactly like a missing one).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: irr-ph7-01",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The controller has no hold in force. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "not_held": {
                    "value": {
                      "error": "not held: the controller's engine is not held",
                      "code": "not_held"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/zones/{device}/{zone}/history": {
      "get": {
        "operationId": "getControlZoneHistory",
        "summary": "A zone's water history in farm days",
        "description": "#365 (CP-5). For each farm day (Asia/Ho_Chi_Minh) from `from` to `to`: the litres of the zone in the day's dispatched program and those the controller reported delivered (and both over the zone's irrigated area, in mm), how the newest program of the day decided the zone, and the ET0 columns of #353 (null until it lands); the zone's runs (newest 500, `truncated`) and the moisture target bands of its signed sheets. Every value is null when its source is absent. An operator: its facilities' controllers; an agronomist: a zone some rule of which rests on a sheet they signed, a day's plan only when it cites one. Served from the server's cache for 60 s. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "path",
            "required": true,
            "description": "The controller's device id.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "name": "zone",
            "in": "path",
            "required": true,
            "description": "The zone number, 1 to 16.",
            "schema": {
              "type": "string"
            },
            "example": "3"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "The first farm date. Default: 13 days before `to`. At most 92 dates in all.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-01"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "The last farm date. Default: today.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-02"
          }
        ],
        "responses": {
          "200": {
            "description": "The zone's history.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlZoneHistory"
                },
                "example": {
                  "generated_at": "2027-03-02T03:15:00Z",
                  "max_age_s": 60,
                  "poll_hint_s": 60,
                  "day": {
                    "date": "2027-03-02",
                    "starts_at": "2027-03-01T17:00:00Z",
                    "time_zone": "Asia/Ho_Chi_Minh"
                  },
                  "from": "2027-03-01",
                  "to": "2027-03-02",
                  "zone": {
                    "device_id": "irr-ph7-01",
                    "zone": 3,
                    "name": "Block A",
                    "area": "VN-TGOR-0387",
                    "irrigated_area_m2": 120.0
                  },
                  "days": [
                    {
                      "date": "2027-03-01",
                      "planned_l": 216.0,
                      "applied_l": 216.0,
                      "planned_mm": 1.8,
                      "applied_mm": 1.8,
                      "et0_mm": null,
                      "et0_status": null,
                      "kc_stage": null,
                      "rain_mm": null,
                      "rule": {
                        "kind": "schedule",
                        "applied_as": "schedule"
                      },
                      "program": {
                        "id": 30,
                        "status": "dispatched"
                      }
                    },
                    {
                      "date": "2027-03-02",
                      "planned_l": null,
                      "applied_l": null,
                      "planned_mm": null,
                      "applied_mm": null,
                      "et0_mm": null,
                      "et0_status": null,
                      "kc_stage": null,
                      "rain_mm": null,
                      "rule": {
                        "kind": "schedule",
                        "applied_as": "blocked: no_signed_sheet"
                      },
                      "program": {
                        "id": 31,
                        "status": "blocked"
                      }
                    }
                  ],
                  "runs": [
                    {
                      "started_at": null,
                      "ended_at": "2027-03-01T13:30:00Z",
                      "litres": 216.0,
                      "source": "program_step",
                      "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f"
                    }
                  ],
                  "moisture_series": {
                    "capability": "soil.moisture",
                    "depth_cm": 30.0,
                    "grain": "hourly"
                  },
                  "moisture": {
                    "capability": "soil.moisture",
                    "grain": "hourly",
                    "bucket_s": 3600.0,
                    "probes": [
                      "soil-07"
                    ],
                    "truncated": false,
                    "series": [
                      {
                        "depth_cm": 30.0,
                        "buckets": [
                          {
                            "bucket_start": 1803906000.0,
                            "min": 30.7,
                            "max": 31.1,
                            "mean": 30.9,
                            "count": 2,
                            "n_total": 2,
                            "n_pass": 2,
                            "n_not_evaluated": 0,
                            "n_suspect": 0,
                            "n_fail": 0,
                            "n_missing": 0
                          },
                          {
                            "bucket_start": 1803909600.0,
                            "min": null,
                            "max": null,
                            "mean": null,
                            "count": 0,
                            "n_total": 1,
                            "n_pass": 0,
                            "n_not_evaluated": 0,
                            "n_suspect": 0,
                            "n_fail": 1,
                            "n_missing": 0
                          }
                        ]
                      }
                    ]
                  },
                  "bands": [],
                  "truncated": false
                }
              }
            }
          },
          "400": {
            "description": "A bad `from` or `to`, `from` after `to`, more than 92 dates, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_from": {
                    "value": {
                      "error": "bad from: a date YYYY-MM-DD",
                      "code": "bad_from"
                    }
                  },
                  "bad_to": {
                    "value": {
                      "error": "bad to: a date YYYY-MM-DD",
                      "code": "bad_to"
                    }
                  },
                  "bad_range": {
                    "value": {
                      "error": "bad range: from must not be after to",
                      "code": "bad_range"
                    }
                  },
                  "range_too_long": {
                    "value": {
                      "error": "range too long",
                      "code": "range_too_long"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers and probes, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such zone of this company: another company's, one outside the caller's grant or an agronomist's sheets answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: irr-ph7-01/3",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/sensor-health": {
      "get": {
        "operationId": "getControlSensorHealth",
        "summary": "The sensor health of a growing area",
        "description": "#365 (CP-5). The area's probes (its field sensors placed now and every probe its zones name, at most 200): each one's link by the health gate's own freshness rule, its hourly coverage and QC counts over the last 30 days, and the enabled threshold rules that read it; and the gate decisions recorded today for the area's zones. An operator: its facilities' probes and controllers; an agronomist: the zones resting on a sheet they signed. Served from the server's cache for 300 s. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "area",
            "in": "query",
            "required": true,
            "description": "The growing area's code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-TGOR-0387"
          }
        ],
        "responses": {
          "200": {
            "description": "The area's sensor health.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlSensorHealth"
                },
                "example": {
                  "generated_at": "2027-03-02T03:15:00Z",
                  "max_age_s": 300,
                  "poll_hint_s": 300,
                  "day": {
                    "date": "2027-03-02",
                    "starts_at": "2027-03-01T17:00:00Z",
                    "time_zone": "Asia/Ho_Chi_Minh"
                  },
                  "area": "VN-TGOR-0387",
                  "probes": [
                    {
                      "device_id": "soil-07",
                      "profile": "vn.agritrace.soil-rs485-4in1",
                      "depth_cm": 30.0,
                      "capability": "soil.moisture",
                      "link": {
                        "state": "stale",
                        "last_obs": "2027-03-02T01:10:00Z",
                        "expected_s": 900.0
                      },
                      "coverage_30d_pct": 96.1,
                      "qc_30d": {
                        "pass": 2710,
                        "not_evaluated": 0,
                        "suspect": 12,
                        "fail": 3,
                        "missing": 0
                      },
                      "used_by": [
                        {
                          "rule_id": 14,
                          "device_id": "irr-ph7-01",
                          "zones": [
                            3
                          ],
                          "state": "fallback:stale",
                          "since": "2027-03-02T02:00:00Z"
                        }
                      ]
                    }
                  ],
                  "gate_decisions_today": [
                    {
                      "rule_id": 14,
                      "device_id": "irr-ph7-01",
                      "zone": 3,
                      "decision": "fallback",
                      "reason": "stale",
                      "at": "2027-03-02T02:00:00Z"
                    }
                  ],
                  "truncated": false
                }
              }
            }
          },
          "400": {
            "description": "A missing or bad `area`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "area_is_required": {
                    "value": {
                      "error": "area is required",
                      "code": "area_is_required"
                    }
                  },
                  "bad_area": {
                    "value": {
                      "error": "bad area: a growing area code",
                      "code": "bad_area"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers and probes, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such growing area for this company, or none of it in the caller's scope (an operator's facilities, an agronomist's sheets): answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: VN-TGOR-0387",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/et0": {
      "get": {
        "operationId": "listControlEt0Days",
        "summary": "List the weather stations' ET0 days",
        "description": "#353. The stored reference evapotranspiration of the weather stations' local days (FAO-56 Penman-Monteith, meteorology only), by station and date, with every input, how it was found, whether it is estimated, and the equations' trace (an operator: the stations of its facilities' zones; an agronomist: those of the zones their sheets' rules water). Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only this controller's.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Local dates (Asia/Ho_Chi_Minh) from this one; by default 6 days before `to`; a year from 2000 to 2100.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-01"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "Local dates up to this one (not before `from`, at most 92 days after it); by default today; a year from 2000 to 2100.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-31"
          }
        ],
        "responses": {
          "200": {
            "description": "The the weather stations' ET0 days.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlEt0Page"
                },
                "example": {
                  "from": "2027-03-01",
                  "to": "2027-03-07",
                  "items": [
                    {
                      "device_id": "wx-ph7-01",
                      "local_date": "2027-03-01",
                      "seq": 1,
                      "wind_height_m": 2.0,
                      "elevation_m": 12.0,
                      "status": "ok",
                      "reason": null,
                      "et0_mm": 4.8123,
                      "inputs": {
                        "latitude_deg": 10.82,
                        "day_of_year": 60,
                        "g": 0.0,
                        "coverage": {
                          "air.temperature": {
                            "readings": 96,
                            "coverage_h": 24,
                            "truncated": false
                          }
                        },
                        "rain": {
                          "mm": 0.0,
                          "method": "measured",
                          "estimated": false
                        },
                        "tmax": 33.1,
                        "tmin": 23.4,
                        "ea": {
                          "value": 2.31,
                          "method": "rh_max_min",
                          "rh_max": 92.0,
                          "rh_min": 48.0,
                          "estimated": false
                        },
                        "u2": {
                          "value": 2.0,
                          "method": "default_2_m_s",
                          "estimated": true
                        },
                        "pressure": {
                          "value": 101.16,
                          "method": "elevation",
                          "estimated": false
                        },
                        "rs": {
                          "value": 20.4,
                          "method": "measured",
                          "estimated": false
                        }
                      },
                      "trace": {
                        "et0_mm": 4.8123,
                        "tmean": 28.25,
                        "pressure_kpa": 101.16,
                        "gamma": 0.0673,
                        "delta": 0.2236,
                        "es": 3.4012,
                        "ea": 2.31,
                        "vpd": 1.0912,
                        "ra": 35.2,
                        "rs": 20.4,
                        "rso": 26.41,
                        "rns": 15.71,
                        "rnl": 3.12,
                        "rn": 12.59,
                        "g": 0.0,
                        "u2": 2.0,
                        "hargreaves_mm": 5.21
                      },
                      "computed_at": 1790007300.5,
                      "estimated": [
                        "u2"
                      ]
                    }
                  ],
                  "truncated": false
                }
              }
            }
          },
          "400": {
            "description": "A bad `device`, `from`, `to` or span (`to` before `from`, or more than 92 days). Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "from": {
                    "value": {
                      "error": "invalid from: a local date YYYY-MM-DD",
                      "code": "invalid_from"
                    }
                  },
                  "to": {
                    "value": {
                      "error": "invalid to: not before from",
                      "code": "invalid_to"
                    }
                  },
                  "span": {
                    "value": {
                      "error": "invalid span: at most 92 days from from to to",
                      "code": "invalid_span"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/budget": {
      "get": {
        "operationId": "listControlBudget",
        "summary": "List the zones' planned and applied water",
        "description": "#353. Per zone of the company's controllers and local date, what the day's last program sent planned (the rule, its mode, the depth at the roots and the litres, the clamps, an ET0 zone's trace) and what the controller reported delivered (an operator: its facilities' controllers; an agronomist: the zones and days of programs citing a sheet they signed). Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only this controller's.",
            "schema": {
              "type": "string"
            },
            "example": "irr-ph7-01"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "Local dates (Asia/Ho_Chi_Minh) from this one; by default 6 days before `to`; a year from 2000 to 2100.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-01"
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "Local dates up to this one (not before `from`, at most 92 days after it); by default today; a year from 2000 to 2100.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "example": "2027-03-31"
          }
        ],
        "responses": {
          "200": {
            "description": "The the zones' planned and applied water.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlBudgetPage"
                },
                "example": {
                  "from": "2027-03-01",
                  "to": "2027-03-07",
                  "items": [
                    {
                      "device_id": "irr-ph7-01",
                      "zone": 3,
                      "name": "Block A, row 1-8",
                      "growing_area": "VT-PH7-03",
                      "local_date": "2027-03-02",
                      "plan": "dispatched",
                      "program_id": 31,
                      "rule_id": 14,
                      "mode": "et0_budget",
                      "planned_mm": 3.85,
                      "planned_l": 10266.667,
                      "clamps": [],
                      "et0": {
                        "station": "wx-ph7-01",
                        "date": "2027-03-01",
                        "status": "ok",
                        "et0_mm": 4.8123,
                        "krs": null,
                        "estimated": [
                          "u2"
                        ],
                        "kc": 0.8,
                        "kc_stage": "flowering",
                        "rain_mm": 0.0,
                        "effective_rain_fraction": 0.8
                      },
                      "applied_l": 9980.0,
                      "applied_mm": 3.7425
                    }
                  ],
                  "truncated": false
                }
              }
            }
          },
          "400": {
            "description": "A bad `device`, `from`, `to` or span (`to` before `from`, or more than 92 days). Or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "from": {
                    "value": {
                      "error": "invalid from: a local date YYYY-MM-DD",
                      "code": "invalid_from"
                    }
                  },
                  "to": {
                    "value": {
                      "error": "invalid to: not before from",
                      "code": "invalid_to"
                    }
                  },
                  "span": {
                    "value": {
                      "error": "invalid span: at most 92 days from from to to",
                      "code": "invalid_span"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/home": {
      "get": {
        "operationId": "getControlHome",
        "summary": "Read the irrigation control home",
        "description": "#354. What needs a person today, for the company's controllers in scope (an operator: its facilities' controllers; an agronomist: what rests on a sheet they signed): how many controllers have a control zone; the programs waiting for a person's approval (their count and the newest 5); the rules by state, with `not_ready` the disabled rules whose sheet would not let them be enabled today (the sheet gate the engine runs on every compose), and at most 10 of them, blocked first, then on fallback, then not ready, each with the engine's reason or the sheet gate's; the open salinity alerts (`salinity_block`, `salinity_alert`: their count and the newest 5); and each weather station's latest stored reference ET0 day (at most 10: meteorology only, a `needs_krs` day has no ET0 of its own, and nothing is filled in that the stored day does not hold). `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The irrigation control home.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlHome"
                },
                "example": {
                  "generated_at": 1790000000.5,
                  "controllers": 1,
                  "programs_waiting": {
                    "count": 1,
                    "items": [
                      {
                        "id": 31,
                        "device_id": "irr-ph7-01",
                        "local_date": "2027-03-02",
                        "proposed_at": 1790000000.5
                      }
                    ]
                  },
                  "rules": {
                    "total": 3,
                    "ok": 1,
                    "blocked": 1,
                    "fallback": 0,
                    "not_ready": 1,
                    "items": [
                      {
                        "id": 14,
                        "name": "Block A ET0",
                        "device_id": "irr-ph7-01",
                        "kind": "et0_budget",
                        "enabled": true,
                        "state": "blocked",
                        "reason": "salinity_block"
                      },
                      {
                        "id": 15,
                        "name": "Block B schedule",
                        "device_id": "irr-ph7-01",
                        "kind": "schedule",
                        "enabled": false,
                        "state": "disabled",
                        "reason": "no_signed_sheet"
                      }
                    ]
                  },
                  "salinity": {
                    "open": 1,
                    "items": [
                      {
                        "id": 88,
                        "kind": "salinity_block",
                        "severity": "high",
                        "device_id": "irr-ph7-01",
                        "created_at": 1790000000.5
                      }
                    ]
                  },
                  "et0": {
                    "items": [
                      {
                        "device_id": "wx-ph7-01",
                        "local_date": "2027-03-01",
                        "status": "ok",
                        "reason": null,
                        "et0_mm": 4.8123,
                        "hargreaves_mm": 5.1022,
                        "estimated": [
                          "u2"
                        ]
                      },
                      {
                        "device_id": "wx-ph7-02",
                        "local_date": "2027-03-01",
                        "status": "needs_krs",
                        "reason": "no_radiation",
                        "et0_mm": null,
                        "hargreaves_mm": 4.9871,
                        "estimated": [
                          "rs"
                        ]
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, operator or agronomist of the company (an operator for its facilities' controllers, an agronomist for what rests on a sheet they signed), or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/advisory": {
      "get": {
        "operationId": "getControlAdvisory",
        "summary": "Read the lime and fertiliser advisory",
        "description": "#354. One item per signed sheet of the company whose validity covers today (the local date, Asia/Ho_Chi_Minh), by series and version: the sheet, who signed it and when, its advisory section exactly as signed (lime and fertiliser: the advice in Vietnamese, English and Simplified Chinese, an optional attachment's SHA-256, and that a lab test is required), its references, and the codes of the company's growing areas of its crop (at most 200; none for a caller who may not read the growing areas: an agronomist holding no other role gets `growing_areas` []); `drafts` counts the company's draft sheets, which are never listed. A signed sheet whose signature can no longer be checked (its stored document no longer hashes to its `body_sha256` and to what its attestation signed, or its signer is no longer verified: the checks a rule's sheet gate makes) is not listed either: `withheld` counts such sheets, with no detail. No amount and no formula: the advice is words only (a sheet's advisory text carries no digit) and the amounts come from a lab test. A sheet is company-wide: an operator reads every one. `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); the advice an agronomist signed is read by a person. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The lime and fertiliser advisory.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlAdvisory"
                },
                "example": {
                  "generated_at": 1790000000.5,
                  "today": "2027-03-02",
                  "items": [
                    {
                      "sheet_id": 7,
                      "series_key": "durian:Ri6:82",
                      "crop": "durian",
                      "version": 2,
                      "valid_from": "2027-01-01",
                      "valid_to": "2027-06-30",
                      "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                      "signed_by": "Nguyễn Văn An",
                      "signed_at": 1790000000.5,
                      "advisory": {
                        "lime": {
                          "text": {
                            "vi": "Bón vôi theo kết quả phân tích đất của phòng thí nghiệm.",
                            "en": "Lime as the laboratory's soil analysis says.",
                            "zh-Hans": "按实验室土壤分析结果施用石灰。"
                          },
                          "requires_lab_test": true
                        },
                        "fertiliser": {
                          "text": {
                            "vi": "Bón phân theo kết quả phân tích đất và lá.",
                            "en": "Fertilise as the soil and leaf analysis says.",
                            "zh-Hans": "按土壤和叶片分析结果施肥。"
                          },
                          "attachment_sha256": "9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b",
                          "requires_lab_test": true
                        }
                      },
                      "references": [
                        {
                          "title": "Provincial durian growing guide",
                          "sha256": "1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c"
                        }
                      ],
                      "growing_areas": [
                        "VT-PH7-03",
                        "VT-PH7-04"
                      ]
                    }
                  ],
                  "drafts": 1,
                  "withheld": 0
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin, auditor, agronomist or operator of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/rules/{id}/resume": {
      "post": {
        "operationId": "resumeControlRule",
        "summary": "Resume a controller's rules over a person's own program",
        "description": "#352. While a person's own set_program (sent by the device command route) is in force on the rule's controller, the engine sends nothing for it: its rules are `blocked` with the reason `manual_override`. Resuming makes every enabled rule of the controller resume over that program: the next compose asserts the engine's program again, with a higher version. 409 `no_override` when no person's program is in force. Needs a recent second-factor proof. Audited (`control_rule.resume`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the staff console.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The record id.",
            "schema": {
              "type": "string"
            },
            "example": "12"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The rule, with the command it resumed over.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlRule"
                },
                "example": {
                  "id": 12,
                  "kind": "schedule",
                  "name": "Block A schedule",
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "sheet_id": 7,
                  "windows": [
                    {
                      "start_local": "05:30",
                      "max_duration_s": 7200
                    }
                  ],
                  "fallback_rule_id": null,
                  "approval": "required",
                  "eval_interval_s": 900,
                  "min_interval_s": 300,
                  "peer_tolerance_pct": null,
                  "min_probes": null,
                  "enabled": true,
                  "state": "ok",
                  "state_reason": null,
                  "state_at": 1790007300.5,
                  "next_run_at": 1790035500.0,
                  "last_run_at": 1790007300.5,
                  "created_by": "admin@coop.example",
                  "created_at": 1790000000.5,
                  "updated_by": "admin@coop.example",
                  "updated_at": 1790000000.5,
                  "enabled_by": "admin@coop.example",
                  "enabled_at": 1790007200.5,
                  "auto_approval_by": null,
                  "auto_approval_at": null,
                  "hold_until": null,
                  "sheet": {
                    "id": 7,
                    "series_key": "durian:Ri6:82",
                    "version": 2,
                    "status": "signed",
                    "body_sha256": "4f1c0a3e9b2d7c6e5a8f0b1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e",
                    "valid_from": "2027-01-01",
                    "valid_to": "2027-06-30"
                  },
                  "sheet_gate": null,
                  "resumed_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f"
                }
              }
            }
          },
          "400": {
            "description": "A bad request. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token. Or a session of an account with two-step sign-in whose code was last confirmed more than 5 minutes ago, or its password more than 10 minutes ago (`mfa_step_up_required`, #87: confirm both with POST /v1/auth/reauth, then repeat the request; nothing was done and no audit row was written).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "credentials": {
                    "value": {
                      "error": "missing or invalid token",
                      "code": "missing_or_invalid_token"
                    }
                  },
                  "step_up": {
                    "value": {
                      "error": "mfa step-up required: confirm your password and a code from your authenticator app with POST /v1/auth/reauth",
                      "code": "mfa_step_up_required"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, or platform_admin acting for it, through a signed-in session only), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such rule of this company: another company's (or one outside the caller's grant) answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: 12",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "No person's program is in force on the controller, or the rule is not enabled. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "no_override": {
                    "value": {
                      "error": "no override: no person's own program is in force on this controller",
                      "code": "no_override"
                    }
                  },
                  "not_enabled": {
                    "value": {
                      "error": "not enabled: the rule is disabled",
                      "code": "not_enabled"
                    }
                  },
                  "idempotency_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/alarms": {
      "get": {
        "operationId": "listAlarms",
        "summary": "List the company's alarms",
        "description": "#361 (ADR 0015). The selected company's alarms: `state=open` (the default: every alarm not closed, shelved ones included) in attention order, urgent, then warning, then notice, the oldest first within a priority (then by id), or `closed`, newest first (by id), optionally of one priority, growing area or device. An operator sees only the alarms of devices in their facilities. `counts` gives the open alarms by priority over every page (null for `closed`). `under` is computed on read (a zone alarm of a controller with an open `controller_offline` alarm is shown under it). At most 4 statements per page, through the alarms' indexes. `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an alarm is acknowledged and shelved by a person. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "alarms"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "state",
            "in": "query",
            "required": false,
            "description": "`open` (the default) or `closed`.",
            "schema": {
              "type": "string",
              "enum": [
                "open",
                "closed"
              ]
            },
            "example": "open"
          },
          {
            "name": "priority",
            "in": "query",
            "required": false,
            "description": "Only alarms of this priority.",
            "schema": {
              "type": "string",
              "enum": [
                "urgent",
                "warning",
                "notice"
              ]
            },
            "example": "urgent"
          },
          {
            "name": "area",
            "in": "query",
            "required": false,
            "description": "Only alarms of this growing area (its code).",
            "schema": {
              "type": "string"
            },
            "example": "VN-LDG-VT03"
          },
          {
            "name": "device",
            "in": "query",
            "required": false,
            "description": "Only alarms of this device.",
            "schema": {
              "type": "string"
            },
            "example": "ctl-03"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "description": "The previous page's `next_cursor`.",
            "schema": {
              "type": "string"
            },
            "example": "eyJpZCI6ODEyfQ"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "description": "At most this many items (1 to 100; 50 by default).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100
            },
            "example": 50
          }
        ],
        "responses": {
          "200": {
            "description": "A page of alarms.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AlarmPage"
                },
                "example": {
                  "items": [
                    {
                      "id": 815,
                      "kind": "delivered_over_limit",
                      "catalog_version": 1,
                      "priority": "urgent",
                      "state": "cleared_unacked",
                      "raised_at": "2026-10-21T23:20:00Z",
                      "last_active_at": "2026-10-21T23:24:00Z",
                      "cleared_at": "2026-10-22T00:05:00Z",
                      "closed_at": null,
                      "occurrences": 1,
                      "acked": null,
                      "shelved": null,
                      "subject": {
                        "type": "zone",
                        "device": "ctl-02",
                        "zone": 1,
                        "area": "VN-LDG-VT02"
                      },
                      "detail": {
                        "command_id": "0b9a8c7d-6e5f-4a3b-9c2d-1e0f9a8b7c6d",
                        "litres": 2150,
                        "max_volume_l": 2000
                      },
                      "response_anchor": "delivered_over_limit",
                      "under": null
                    },
                    {
                      "id": 812,
                      "kind": "command_refused_site",
                      "catalog_version": 1,
                      "priority": "warning",
                      "state": "active_unacked",
                      "raised_at": "2026-10-22T05:12:00Z",
                      "last_active_at": "2026-10-22T07:31:00Z",
                      "cleared_at": null,
                      "closed_at": null,
                      "occurrences": 1,
                      "acked": null,
                      "shelved": null,
                      "subject": {
                        "type": "zone",
                        "device": "ctl-03",
                        "zone": 3,
                        "area": "VN-LDG-VT03"
                      },
                      "detail": {
                        "command_id": "6f1d2c3b-8a4e-4f0b-9c7d-1e2f3a4b5c6d",
                        "reason": "manual_override_active"
                      },
                      "response_anchor": "command_refused_site",
                      "under": null
                    }
                  ],
                  "next_cursor": null,
                  "counts": {
                    "urgent": 1,
                    "warning": 1,
                    "notice": 0,
                    "shelved": 0
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad `state`, `priority`, `area`, `device`, `cursor` or `limit`, or a bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "state": {
                    "value": {
                      "error": "bad state: open or closed",
                      "code": "bad_state"
                    }
                  },
                  "priority": {
                    "value": {
                      "error": "bad priority: urgent, warning or notice",
                      "code": "bad_priority"
                    }
                  },
                  "limit": {
                    "value": {
                      "error": "bad limit: 1 to 100",
                      "code": "bad_limit"
                    }
                  },
                  "cursor": {
                    "value": {
                      "error": "bad cursor",
                      "code": "bad_cursor"
                    }
                  },
                  "area": {
                    "value": {
                      "error": "bad area: a growing area code",
                      "code": "bad_area"
                    }
                  },
                  "device": {
                    "value": {
                      "error": "bad device: a device id",
                      "code": "bad_device"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or auditor of the company, operator of the company within its facilities, agronomist of the company for the controllers and zones of the rules bound to a sheet they signed, or platform_admin acting for it, through a signed-in session only; lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/alarms/{id}": {
      "get": {
        "operationId": "getAlarm",
        "summary": "Read an alarm and its history",
        "description": "#361 (ADR 0015). One alarm of the selected company with its events (`alarm_events`, append-only): oldest first, at most the 100 newest. `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an alarm is acknowledged and shelved by a person. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "alarms"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The alarm id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "812"
          }
        ],
        "responses": {
          "200": {
            "description": "The alarm with its events.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AlarmDetail"
                },
                "example": {
                  "id": 812,
                  "kind": "command_refused_site",
                  "catalog_version": 1,
                  "priority": "warning",
                  "state": "active_acked",
                  "raised_at": "2026-10-22T05:12:00Z",
                  "last_active_at": "2026-10-22T07:31:00Z",
                  "cleared_at": null,
                  "closed_at": null,
                  "occurrences": 1,
                  "acked": {
                    "at": "2026-10-22T07:40:00Z",
                    "by": "Trần Thị Lan",
                    "note": "Switch back to AUTO after the repair"
                  },
                  "shelved": null,
                  "subject": {
                    "type": "zone",
                    "device": "ctl-03",
                    "zone": 3,
                    "area": "VN-LDG-VT03"
                  },
                  "detail": {
                    "command_id": "6f1d2c3b-8a4e-4f0b-9c7d-1e2f3a4b5c6d",
                    "reason": "manual_override_active"
                  },
                  "response_anchor": "command_refused_site",
                  "under": null,
                  "events": [
                    {
                      "at": "2026-10-22T05:12:00Z",
                      "event": "raised",
                      "actor": "system",
                      "reason": null
                    },
                    {
                      "at": "2026-10-22T07:40:00Z",
                      "event": "acked",
                      "actor": "Trần Thị Lan",
                      "reason": null
                    }
                  ],
                  "events_truncated": false
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequestId"
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or auditor of the company, operator of the company within its facilities, agronomist of the company for the controllers and zones of the rules bound to a sheet they signed, or platform_admin acting for it, through a signed-in session only; lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such alarm of this company within the caller's facilities: another company's, a missing one and one of a device outside an operator's facilities all answer alike.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: alarm",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/alarms/{id}/ack": {
      "post": {
        "operationId": "acknowledgeAlarm",
        "summary": "Acknowledge an alarm",
        "description": "#361 (ADR 0015 §2). A person records that they know of the alarm, with an optional note: an active alarm becomes `active_acked`, a cleared one closes. Idempotent: an alarm already acknowledged, or closed, answers 200 unchanged (no event). Audited (`alarm.ack`: the alarm's state before and after); the change and its `alarm_events` row commit together. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an alarm is acknowledged and shelved by a person. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "alarms"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The alarm id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "812"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AlarmAck"
              },
              "example": {
                "note": "Switch back to AUTO after the repair"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The alarm as it is now.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AlarmView"
                },
                "example": {
                  "id": 812,
                  "kind": "command_refused_site",
                  "catalog_version": 1,
                  "priority": "warning",
                  "state": "active_acked",
                  "raised_at": "2026-10-22T05:12:00Z",
                  "last_active_at": "2026-10-22T07:31:00Z",
                  "cleared_at": null,
                  "closed_at": null,
                  "occurrences": 1,
                  "acked": {
                    "at": "2026-10-22T07:40:00Z",
                    "by": "Trần Thị Lan",
                    "note": "Switch back to AUTO after the repair"
                  },
                  "shelved": null,
                  "subject": {
                    "type": "zone",
                    "device": "ctl-03",
                    "zone": 3,
                    "area": "VN-LDG-VT03"
                  },
                  "detail": {
                    "command_id": "6f1d2c3b-8a4e-4f0b-9c7d-1e2f3a4b5c6d",
                    "reason": "manual_override_active"
                  },
                  "response_anchor": "command_refused_site",
                  "under": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, or a note over 500 characters. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "note": {
                    "value": {
                      "error": "bad note: at most 500 characters",
                      "code": "bad_note"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, operator of the company within its facilities, or platform_admin acting for it, through a signed-in session only; auditors, agronomists and lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such alarm of this company within the caller's facilities: another company's, a missing one and one of a device outside an operator's facilities all answer alike.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: alarm",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "idempotency key in use: retry later",
                  "code": "idempotency_key_in_use"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/alarms/{id}/shelve": {
      "post": {
        "operationId": "shelveAlarm",
        "summary": "Shelve an alarm until a time",
        "description": "#361 (ADR 0015 §2). Hides an open alarm from the attention lists until `until` (at most 12 hours ahead for an urgent alarm, 72 hours for a warning or a notice), with a reason from the list and a note (required for `other`). It returns by itself at that time (event `shelve_expired`) or when unshelved; its condition is still evaluated meanwhile. Shelving a shelved alarm again replaces its end. Audited (`alarm.shelve`: the end and the reason). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an alarm is acknowledged and shelved by a person. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "alarms"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The alarm id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "812"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AlarmShelve"
              },
              "example": {
                "until": "2026-10-22T23:00:00Z",
                "reason": "technician_called"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The alarm as it is now.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AlarmView"
                },
                "example": {
                  "id": 812,
                  "kind": "command_refused_site",
                  "catalog_version": 1,
                  "priority": "warning",
                  "state": "shelved",
                  "raised_at": "2026-10-22T05:12:00Z",
                  "last_active_at": "2026-10-22T07:31:00Z",
                  "cleared_at": null,
                  "closed_at": null,
                  "occurrences": 1,
                  "acked": null,
                  "shelved": {
                    "until": "2026-10-22T23:00:00Z",
                    "by": "Trần Thị Lan",
                    "reason": "technician_called",
                    "note": null
                  },
                  "subject": {
                    "type": "zone",
                    "device": "ctl-03",
                    "zone": 3,
                    "area": "VN-LDG-VT03"
                  },
                  "detail": {
                    "command_id": "6f1d2c3b-8a4e-4f0b-9c7d-1e2f3a4b5c6d",
                    "reason": "manual_override_active"
                  },
                  "response_anchor": "command_refused_site",
                  "under": null
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, an unknown field, an `until` that is not an RFC 3339 time in the future, an unknown reason, a missing or too long note, or an end past the priority's maximum. Or a bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalid_json": {
                    "value": {
                      "error": "invalid JSON",
                      "code": "invalid_json"
                    }
                  },
                  "until": {
                    "value": {
                      "error": "bad until: an RFC 3339 time in the future",
                      "code": "bad_until"
                    }
                  },
                  "reason": {
                    "value": {
                      "error": "bad reason: one of maintenance, technician_called, known_issue, equipment_off, other",
                      "code": "bad_reason"
                    }
                  },
                  "note": {
                    "value": {
                      "error": "bad note: 1 to 200 characters, required when the reason is other",
                      "code": "bad_note"
                    }
                  },
                  "too_long": {
                    "value": {
                      "error": "shelve too long: at most 12 h for an urgent alarm",
                      "code": "shelve_too_long"
                    }
                  },
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, operator of the company within its facilities, or platform_admin acting for it, through a signed-in session only; auditors, agronomists and lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such alarm of this company within the caller's facilities: another company's, a missing one and one of a device outside an operator's facilities all answer alike.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: alarm",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The alarm is closed. Or the Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "alarm_closed": {
                    "value": {
                      "error": "alarm closed: a closed alarm cannot be shelved",
                      "code": "alarm_closed"
                    }
                  },
                  "idempotency_key_in_use": {
                    "value": {
                      "error": "idempotency key in use: retry later",
                      "code": "idempotency_key_in_use"
                    }
                  }
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/alarms/{id}/unshelve": {
      "post": {
        "operationId": "unshelveAlarm",
        "summary": "End an alarm's shelving",
        "description": "#361 (ADR 0015 §2). The alarm returns to the attention lists now. An alarm that is not shelved answers 200 unchanged (no event). Audited (`alarm.unshelve`). Through a signed-in session only: an API token, an API client or the legacy token is refused (403); an alarm is acknowledged and shelved by a person. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "alarms"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The alarm id.",
            "schema": {
              "type": "string",
              "pattern": "^[1-9][0-9]{0,17}$"
            },
            "example": "812"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          }
        ],
        "responses": {
          "200": {
            "description": "The alarm as it is now.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AlarmView"
                },
                "example": {
                  "id": 812,
                  "kind": "command_refused_site",
                  "catalog_version": 1,
                  "priority": "warning",
                  "state": "active_unacked",
                  "raised_at": "2026-10-22T05:12:00Z",
                  "last_active_at": "2026-10-22T07:31:00Z",
                  "cleared_at": null,
                  "closed_at": null,
                  "occurrences": 1,
                  "acked": null,
                  "shelved": null,
                  "subject": {
                    "type": "zone",
                    "device": "ctl-03",
                    "zone": 3,
                    "area": "VN-LDG-VT03"
                  },
                  "detail": {
                    "command_id": "6f1d2c3b-8a4e-4f0b-9c7d-1e2f3a4b5c6d",
                    "reason": "manual_override_active"
                  },
                  "response_anchor": "command_refused_site",
                  "under": null
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id, or a malformed or repeated Idempotency-Key header.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "bad_request_id": {
                    "value": {
                      "error": "bad request id",
                      "code": "bad_request_id"
                    }
                  },
                  "invalid_idempotency_key": {
                    "value": {
                      "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                      "code": "invalid_idempotency_key"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin of the company, operator of the company within its facilities, or platform_admin acting for it, through a signed-in session only; auditors, agronomists and lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in), origin not allowed or CSRF token missing or invalid (cookie sessions on unsafe methods), company read-only (SELF-2-4, #193: the company is leaving CropPath or has left).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  },
                  "csrf": {
                    "value": {
                      "error": "csrf token missing or invalid",
                      "code": "csrf_token_missing_or_invalid"
                    }
                  },
                  "origin": {
                    "value": {
                      "error": "origin not allowed",
                      "code": "origin_not_allowed"
                    }
                  },
                  "company_read_only": {
                    "value": {
                      "error": "company read-only: the company is leaving or has left CropPath; its records can be read and exported but not changed",
                      "code": "company_read_only"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such alarm of this company within the caller's facilities: another company's, a missing one and one of a device outside an operator's facilities all answer alike.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: alarm",
                  "code": "not_found"
                }
              }
            }
          },
          "409": {
            "description": "The Idempotency-Key's first request is still running, or its response cannot be replayed.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "idempotency key in use: retry later",
                  "code": "idempotency_key_in_use"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "$ref": "#/components/responses/IdempotencyKeyMismatch"
          }
        }
      }
    },
    "/v1/control/fleet-state": {
      "get": {
        "operationId": "getControlFleetState",
        "summary": "The company's water today",
        "description": "#363 (CP-4 of #357). What needs attention, each growing area that holds an irrigation controller and each controller, from what the controllers and gateways reported. An operator reads the controllers and alarms of their facilities; an agronomist those of the rules bound to a sheet they signed. Served from a 10 s server cache (`max_age_s`); poll every `poll_hint_s`. At most 15 statements cold, 0 warm. `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "responses": {
          "200": {
            "description": "The company's water today.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlFleetState"
                },
                "example": {
                  "tenant": "coop-dl",
                  "generated_at": "2026-10-22T07:32:05Z",
                  "max_age_s": 10,
                  "poll_hint_s": 15,
                  "day": {
                    "date": "2026-10-22",
                    "starts_at": "2026-10-21T17:00:00Z",
                    "time_zone": "Asia/Ho_Chi_Minh"
                  },
                  "view": "admin",
                  "attention": {
                    "state": "ok",
                    "alarms": {
                      "urgent": 0,
                      "warning": 1,
                      "notice": 0,
                      "shelved": 1
                    },
                    "items": [
                      {
                        "type": "alarm",
                        "id": 812,
                        "kind": "command_refused_site",
                        "priority": "warning",
                        "state": "active_unacked",
                        "since": "2026-10-21T22:12:00Z",
                        "subject": {
                          "area": "VN-LDG-VT03",
                          "device": "ctl-03",
                          "zone": 3
                        },
                        "words_key": "manual_override_active",
                        "can_ack": true
                      },
                      {
                        "type": "task",
                        "kind": "program_waiting_approval",
                        "program_id": 31,
                        "device": "ctl-03",
                        "since": "2026-10-21T17:05:00Z"
                      }
                    ],
                    "capped": false
                  },
                  "areas": {
                    "state": "ok",
                    "items": [
                      {
                        "code": "VN-LDG-VT03",
                        "name": "Garden 3",
                        "controllers": {
                          "total": 1,
                          "online": 1,
                          "stale": 0,
                          "offline": 0,
                          "unknown": 0
                        },
                        "zones": {
                          "total": 6,
                          "running": 1,
                          "scheduled_now": 0
                        },
                        "water_today": {
                          "applied_l": 4120.0,
                          "planned_l": null,
                          "plan": "blocked",
                          "reason": "no_signed_sheet"
                        },
                        "sensors": {
                          "total": 4,
                          "stale": 1
                        },
                        "alarms": {
                          "urgent": 0,
                          "warning": 1,
                          "notice": 0
                        }
                      }
                    ],
                    "capped": false
                  },
                  "controllers": {
                    "state": "ok",
                    "running_or_outstanding": true,
                    "items": [
                      {
                        "device_id": "ctl-03",
                        "name": "Controller 3",
                        "area": "VN-LDG-VT03",
                        "link": {
                          "state": "online",
                          "via": "gateway",
                          "gateway": "gw-v3",
                          "heard_at": "2026-10-22T07:31:50Z",
                          "expected_s": 30,
                          "ready": true
                        },
                        "lease": {
                          "program_version": 41,
                          "valid_until": "2026-10-22T17:00:00Z"
                        }
                      }
                    ],
                    "capped": false
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or auditor of the company, operator of the company within its facilities, agronomist of the company for the controllers and zones of the rules bound to a sheet they signed, or platform_admin acting for it, through a signed-in session only; lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "The selected company does not exist (a platform admin naming one with X-Tenant).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: company",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/areas/{code}/today": {
      "get": {
        "operationId": "getControlAreaToday",
        "summary": "An area's irrigation day",
        "description": "#363 (CP-4 of #357). The day of the irrigation controllers placed in one growing area of the company: each controller's link, today's program, its zones (state from the reports only, today's water against the rules' plan, soil moisture against the signed sheet's band), its lease's steps and its newest commands. Served from a 10 s server cache. At most 12 statements cold, 0 warm. `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "code",
            "in": "path",
            "required": true,
            "description": "The growing area code.",
            "schema": {
              "type": "string"
            },
            "example": "VN-LDG-VT03"
          }
        ],
        "responses": {
          "200": {
            "description": "An area's irrigation day.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlAreaToday"
                },
                "example": {
                  "generated_at": "2026-10-22T07:32:05Z",
                  "max_age_s": 10,
                  "poll_hint_s": 15,
                  "day": {
                    "date": "2026-10-22",
                    "starts_at": "2026-10-21T17:00:00Z",
                    "time_zone": "Asia/Ho_Chi_Minh"
                  },
                  "area": {
                    "code": "VN-LDG-VT03",
                    "name": "Garden 3"
                  },
                  "controllers": [
                    {
                      "device_id": "ctl-03",
                      "name": "Controller 3",
                      "link": {
                        "state": "online",
                        "via": "gateway",
                        "gateway": "gw-v3",
                        "heard_at": "2026-10-22T07:31:50Z",
                        "expected_s": 30,
                        "ready": true
                      },
                      "hold_until": null,
                      "program": {
                        "state": "installed",
                        "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                        "program_version": 41,
                        "control_program_id": 31,
                        "valid_until": "2026-10-22T17:00:00Z",
                        "withdrawable": true,
                        "withdraw_effect": "stop_installed",
                        "withdrawal": null,
                        "lease_version": 41,
                        "lease_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                        "lease_control_program_id": 31
                      },
                      "zones": [
                        {
                          "zone": 3,
                          "name": "Rows 1-4",
                          "state": "running",
                          "source": "run_zone_reply",
                          "since": "2026-10-22T07:03:00Z",
                          "expected_end": "2026-10-22T07:23:00Z",
                          "reason": null,
                          "today": {
                            "applied_l": 840.0,
                            "planned_l": null,
                            "runs": 1
                          },
                          "moisture": {
                            "state": "no_band",
                            "value_pct": 28.4,
                            "obs_time": "2026-10-22T07:26:00Z",
                            "band": {
                              "lower_pct": null,
                              "upper_pct": null,
                              "sheet": null
                            }
                          },
                          "sheet": null
                        }
                      ],
                      "steps": [
                        {
                          "zone": 3,
                          "start_s": 21600,
                          "duration_s": 1200,
                          "max_volume_l": 2625,
                          "planned_l": null,
                          "actual": {
                            "state": "done",
                            "litres": 1980.0,
                            "ended_at": "2026-10-21T23:20:40Z"
                          }
                        }
                      ],
                      "commands": [
                        {
                          "id": "9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f",
                          "name": "run_zone",
                          "status": "accepted",
                          "issued_by": "Lan",
                          "issued_at": "2026-10-22T07:02:10Z",
                          "params": {
                            "zone": 3,
                            "duration_s": 1200,
                            "max_volume_l": 2000
                          },
                          "expires_at": "2026-10-22T07:07:10Z",
                          "reason": null,
                          "measured": null
                        }
                      ]
                    }
                  ],
                  "truncated": false
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or auditor of the company, operator of the company within its facilities, agronomist of the company for the controllers and zones of the rules bound to a sheet they signed, or platform_admin acting for it, through a signed-in session only; lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "No such area of this company, or none of its controllers is in the caller's facilities or rules: each answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: area",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/v1/control/controllers/{id}/today": {
      "get": {
        "operationId": "getControlControllerToday",
        "summary": "A controller's irrigation day",
        "description": "#363 (CP-4 of #357). One irrigation controller's day in the shape of a controller of the area's day, with its profile's run_zone limits and its zones' nominal flow and daily cap (#352 control_zones: installation facts, not agronomy). Served from a 10 s server cache. At most 11 statements cold, 0 warm. `no-store`. Read-only and not audited. Through a signed-in session only: an API token, an API client or the legacy token is refused (403); irrigation control is a person's decision about water. Not part of the partner SDK clients (`x-not-in-sdk`): an operation of the irrigation cockpit.",
        "tags": [
          "control"
        ],
        "security": [
          {
            "cookie": []
          }
        ],
        "x-session-only": true,
        "x-not-in-sdk": true,
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "The controller's device id.",
            "schema": {
              "type": "string"
            },
            "example": "ctl-03"
          }
        ],
        "responses": {
          "200": {
            "description": "A controller's irrigation day.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              },
              "Cache-Control": {
                "description": "`no-store`.",
                "schema": {
                  "type": "string"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ControlControllerDay"
                },
                "examples": {
                  "installed": {
                    "summary": "A program installed, a zone running by hand",
                    "value": {
                      "generated_at": "2026-10-22T07:32:05Z",
                      "max_age_s": 10,
                      "poll_hint_s": 15,
                      "day": {
                        "date": "2026-10-22",
                        "starts_at": "2026-10-21T17:00:00Z",
                        "time_zone": "Asia/Ho_Chi_Minh"
                      },
                      "device_id": "ctl-03",
                      "name": "Controller 3",
                      "link": {
                        "state": "online",
                        "via": "gateway",
                        "gateway": "gw-v3",
                        "heard_at": "2026-10-22T07:31:50Z",
                        "expected_s": 30,
                        "ready": true
                      },
                      "hold_until": null,
                      "program": {
                        "state": "installed",
                        "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                        "program_version": 41,
                        "control_program_id": 31,
                        "valid_until": "2026-10-22T17:00:00Z",
                        "withdrawable": true,
                        "withdraw_effect": "stop_installed",
                        "withdrawal": null,
                        "lease_version": 41,
                        "lease_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                        "lease_control_program_id": 31
                      },
                      "zones": [
                        {
                          "zone": 3,
                          "name": "Rows 1-4",
                          "state": "running",
                          "source": "run_zone_reply",
                          "since": "2026-10-22T07:03:00Z",
                          "expected_end": "2026-10-22T07:23:00Z",
                          "reason": null,
                          "today": {
                            "applied_l": 840.0,
                            "planned_l": null,
                            "runs": 1
                          },
                          "moisture": {
                            "state": "no_band",
                            "value_pct": 28.4,
                            "obs_time": "2026-10-22T07:26:00Z",
                            "band": {
                              "lower_pct": null,
                              "upper_pct": null,
                              "sheet": null
                            }
                          },
                          "sheet": null,
                          "nominal_flow_lpm": 100.0,
                          "max_daily_l": 5000.0
                        }
                      ],
                      "steps": [
                        {
                          "zone": 3,
                          "start_s": 21600,
                          "duration_s": 1200,
                          "max_volume_l": 2625,
                          "planned_l": null,
                          "actual": {
                            "state": "done",
                            "litres": 1980.0,
                            "ended_at": "2026-10-21T23:20:40Z"
                          }
                        }
                      ],
                      "commands": [
                        {
                          "id": "9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f",
                          "name": "run_zone",
                          "status": "accepted",
                          "issued_by": "Lan",
                          "issued_at": "2026-10-22T07:02:10Z",
                          "params": {
                            "zone": 3,
                            "duration_s": 1200,
                            "max_volume_l": 2000
                          },
                          "expires_at": "2026-10-22T07:07:10Z",
                          "reason": null,
                          "measured": null
                        }
                      ],
                      "area": {
                        "code": "VN-LDG-VT03"
                      },
                      "limits": {
                        "duration_s_min": 1,
                        "duration_s_max": 3600,
                        "max_volume_l_min": 1,
                        "max_volume_l_max": 20000,
                        "max_expiry_s": 300
                      },
                      "truncated": false
                    }
                  },
                  "withdrawn": {
                    "summary": "Today's program withdrawn (the 16:00 step withdrawn, the controller held until midnight), the zone's rule bound to a signed sheet",
                    "value": {
                      "generated_at": "2026-10-22T07:32:05Z",
                      "max_age_s": 10,
                      "poll_hint_s": 15,
                      "day": {
                        "date": "2026-10-22",
                        "starts_at": "2026-10-21T17:00:00Z",
                        "time_zone": "Asia/Ho_Chi_Minh"
                      },
                      "device_id": "ctl-03",
                      "name": "Controller 3",
                      "link": {
                        "state": "online",
                        "via": "gateway",
                        "gateway": "gw-v3",
                        "heard_at": "2026-10-22T07:31:50Z",
                        "expected_s": 30,
                        "ready": true
                      },
                      "hold_until": "2026-10-22T17:00:00Z",
                      "program": {
                        "state": "ended",
                        "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                        "program_version": 41,
                        "control_program_id": 31,
                        "valid_until": "2026-10-22T17:00:00Z",
                        "withdrawable": true,
                        "withdraw_effect": "already_held",
                        "withdrawal": {
                          "requested_at": "2026-10-22T07:00:00Z",
                          "published": true,
                          "reason": "Rain since noon"
                        },
                        "lease_version": 41,
                        "lease_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                        "lease_control_program_id": 31
                      },
                      "zones": [
                        {
                          "zone": 3,
                          "name": "Rows 1-4",
                          "state": "running",
                          "source": "run_zone_reply",
                          "since": "2026-10-22T07:03:00Z",
                          "expected_end": "2026-10-22T07:23:00Z",
                          "reason": null,
                          "today": {
                            "applied_l": 840.0,
                            "planned_l": null,
                            "runs": 1
                          },
                          "moisture": {
                            "state": "no_band",
                            "value_pct": 28.4,
                            "obs_time": "2026-10-22T07:26:00Z",
                            "band": {
                              "lower_pct": null,
                              "upper_pct": null,
                              "sheet": null
                            }
                          },
                          "sheet": {
                            "id": 7,
                            "status": "signed",
                            "version": 3,
                            "stage": "flowering",
                            "stage_name": {
                              "vi": "Ra hoa",
                              "en": "Flowering",
                              "zh-Hans": "开花期"
                            }
                          },
                          "nominal_flow_lpm": 100.0,
                          "max_daily_l": 5000.0
                        }
                      ],
                      "steps": [
                        {
                          "zone": 3,
                          "start_s": 21600,
                          "duration_s": 1200,
                          "max_volume_l": 2625,
                          "planned_l": null,
                          "actual": {
                            "state": "done",
                            "litres": 1980.0,
                            "ended_at": "2026-10-21T23:20:40Z"
                          }
                        },
                        {
                          "zone": 3,
                          "start_s": 57600,
                          "duration_s": 1200,
                          "max_volume_l": 2625,
                          "planned_l": null,
                          "actual": {
                            "state": "withdrawn",
                            "litres": null,
                            "ended_at": null
                          }
                        }
                      ],
                      "commands": [
                        {
                          "id": "9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f",
                          "name": "run_zone",
                          "status": "accepted",
                          "issued_by": "Lan",
                          "issued_at": "2026-10-22T07:02:10Z",
                          "params": {
                            "zone": 3,
                            "duration_s": 1200,
                            "max_volume_l": 2000
                          },
                          "expires_at": "2026-10-22T07:07:10Z",
                          "reason": null,
                          "measured": null
                        }
                      ],
                      "area": {
                        "code": "VN-LDG-VT03"
                      },
                      "limits": {
                        "duration_s_min": 1,
                        "duration_s_max": 3600,
                        "max_volume_l_min": 1,
                        "max_volume_l_max": 20000,
                        "max_expiry_s": 300
                      },
                      "truncated": false
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "A bad X-Request-Id.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              }
            }
          },
          "401": {
            "description": "No valid session, API token or legacy token.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "missing or invalid token",
                  "code": "missing_or_invalid_token"
                }
              }
            }
          },
          "403": {
            "description": "The caller is known but refused: role not permitted (tenant_admin or auditor of the company, operator of the company within its facilities, agronomist of the company for the controllers and zones of the rules bound to a sheet they signed, or platform_admin acting for it, through a signed-in session only; lab users are refused), tenant not allowed (X-Tenant), two-factor required (the company requires two-step sign-in).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "role": {
                    "value": {
                      "error": "role not permitted",
                      "code": "role_not_permitted"
                    }
                  },
                  "tenant": {
                    "value": {
                      "error": "tenant not allowed",
                      "code": "tenant_not_allowed"
                    }
                  },
                  "two_factor": {
                    "value": {
                      "error": "two-factor required: set up two-step sign-in for this account",
                      "code": "two_factor_required"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Not an irrigation controller of this company, or outside the caller's facilities or rules: each answers exactly like a missing one.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/X-Request-Id"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "not found: device",
                  "code": "not_found"
                }
              }
            }
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "cookie": {
        "type": "apiKey",
        "in": "cookie",
        "name": "__Host-agt_sid",
        "description": "Server session cookie. In the plain-HTTP insecure dev mode the cookie is named `agt_sid`. Unsafe methods (POST, PUT, PATCH, DELETE) also need an `X-CSRF-Token` header equal to the session's csrf_token and an allowed Origin."
      },
      "bearer": {
        "type": "http",
        "scheme": "bearer",
        "description": "A hashed API token (`agt_...`), an OAuth2 access token from POST /v1/oauth/token (`ago_...`, limited to its scopes), or a legacy AGRITRACE_API_TOKENS principal (role tenant_admin). Exempt from CSRF."
      },
      "oauth2": {
        "type": "oauth2",
        "description": "OAuth2 client credentials (RFC 6749 §4.4, #171): a tenant admin registers an API client (POST /v1/oauth-clients) with a role and scopes; the client exchanges its id and secret at POST /v1/oauth/token for a 15-minute access token (`ago_...`), sent as `Authorization: Bearer`. A token opens an operation only when the operation lists the token's scope here, and its client's role allows it; otherwise 403 `role not permitted`. A scope is the name of one route permission and implies no other: `epcis_capture` and `records_export` in particular are granted only by name.",
        "flows": {
          "clientCredentials": {
            "tokenUrl": "/v1/oauth/token",
            "scopes": {
              "aggregate_read": "The `aggregate_read` permission. Operations: GET /v1/volumes/{growing_area}/{season}.",
              "attachment_read": "The `attachment_read` permission. Operations: GET /v1/attachments/{sha256}, GET /v1/attachments/{sha256}/peaks.",
              "attachment_upload": "The `attachment_upload` permission. Operations: PUT /v1/attachments/{sha256}.",
              "command_read": "The `command_read` permission. Operations: GET /v1/commands/{id}, GET /v1/devices/{id}/commands.",
              "device_admin": "The `device_admin` permission. Operations: PATCH /v1/devices/{id}, POST /v1/devices, POST /v1/gateways, POST /v1/harvest-keys/{kid}/approve, POST /v1/harvest-keys/{kid}/reject, POST /v1/keys, POST /v1/keys/{kid}/revoke.",
              "device_command": "The `device_command` permission. Operations: POST /v1/devices/{id}/commands.",
              "device_read": "The `device_read` permission. Operations: GET /v1/devices, GET /v1/devices/{id}.",
              "envelope_read": "The `envelope_read` permission. Operations: GET /v1/envelopes, GET /v1/envelopes/stream, GET /v1/envelopes/{id}.",
              "epcis_capture": "Capture of partner EPCIS 2.0 documents (#167). A dedicated scope: no other scope implies it. Operations: POST /v1/epcis/capture.",
              "facility_edit": "The `facility_edit` permission. Operations: PATCH /v1/facilities/{code}.",
              "facility_read": "The `facility_read` permission. Operations: GET /v1/facilities, GET /v1/facilities/{code}, GET /v1/facilities/{code}/issuer-keys.",
              "fruit_action": "The `fruit_action` permission. Operations: POST /v1/fruits/{code}/actions.",
              "grading_rule_read": "The `grading_rule_read` permission. Operations: GET /v1/grading-rules, GET /v1/grading-rules/{variety}/history.",
              "grading_rule_write": "The `grading_rule_write` permission. Operations: PUT /v1/grading-rules/{variety}.",
              "growing_area_edit": "The `growing_area_edit` permission. Operations: PATCH /v1/growers/{id}, PATCH /v1/growing-areas/{code}, POST /v1/growers, POST /v1/growers/batch, POST /v1/growing-areas, POST /v1/growing-areas/{code}/certifications, POST /v1/growing-areas/{code}/harvests, POST /v1/growing-areas/{code}/satellite-checks, POST /v1/growing-areas/{code}/sprays, POST /v1/harvests/batch.",
              "growing_area_read": "The `growing_area_read` permission. Operations: GET /v1/growers, GET /v1/growers/{id}, GET /v1/growing-areas, GET /v1/growing-areas/{code}, GET /v1/growing-areas/{code}/certifications, GET /v1/growing-areas/{code}/harvests, GET /v1/growing-areas/{code}/mass-balance, GET /v1/growing-areas/{code}/satellite-checks, GET /v1/growing-areas/{code}/sprays, GET /v1/growing-areas/{code}/volume.",
              "issuer_key_admin": "The `issuer_key_admin` permission. Operations: POST /v1/facilities/{code}/issuer-keys, POST /v1/facilities/{code}/issuer-keys/{key}/revoke.",
              "lot_read": "The `lot_read` permission. Operations: GET /v1/cartons/{code}, GET /v1/fruits/{code}, GET /v1/lots, GET /v1/lots/{lot}, GET /v1/lots/{lot}/captured-events, GET /v1/lots/{lot}/cartons, GET /v1/lots/{lot}/close-check, GET /v1/lots/{lot}/export-label, GET /v1/lots/{lot}/fruits, GET /v1/lots/{lot}/manifest, GET /v1/lots/{lot}/packing, GET /v1/lots/{lot}/samples, GET /v1/lots/{lot}/sessions, GET /v1/lots/{lot}/summary, GET /v1/lots/{lot}/trust, GET /v1/sessions/{id}, GET /v1/sessions/{id}/feed, GET /v1/sessions/{id}/fruits, GET /v1/sessions/{id}/stream, GET /v1/shipments/{code}.",
              "lot_recall": "The `lot_recall` permission. Operations: POST /v1/lots/{lot}/recall.",
              "lot_write": "The `lot_write` permission. Operations: PATCH /v1/lots/{lot}, POST /v1/lots, POST /v1/lots/{lot}/carton-contents/batch, POST /v1/lots/{lot}/cartons, POST /v1/lots/{lot}/cartons/batch, POST /v1/lots/{lot}/close, POST /v1/lots/{lot}/export-label/prints, POST /v1/lots/{lot}/samples, POST /v1/lots/{lot}/seal, POST /v1/lots/{lot}/sessions, POST /v1/sessions/{id}/close, POST /v1/sessions/{id}/fruits, POST /v1/sessions/{id}/fruits/batch, POST /v1/sessions/{id}/pause, POST /v1/sessions/{id}/resume, POST /v1/shipments, POST /v1/shipments/{code}/depart, POST /v1/shipments/{code}/logger-readings, POST /v1/shipments/{code}/lots, PUT /v1/cartons/{code}/fruits, PUT /v1/shipments/{code}/consignee, PUT /v1/shipments/{code}/documents.",
              "market_limit_read": "The `market_limit_read` permission. Operations: GET /v1/market-limits.",
              "recall_read": "The `recall_read` permission. Operations: GET /v1/lots/{lot}/recall-export.csv, GET /v1/lots/{lot}/recall-export.json, GET /v1/lots/{lot}/trace.",
              "records_export": "The records-request exports of a lot or of a date range (#152). A dedicated scope: no other scope implies it. Operations: GET /v1/lots/{lot}/records-export.csv, GET /v1/lots/{lot}/records-export.json, GET /v1/records-export.csv, GET /v1/records-export.json.",
              "report_triage": "The `report_triage` permission. Operations: GET /v1/reports, GET /v1/reports/{id}, POST /v1/reports/{id}/resolve.",
              "review": "The `review` permission. Operations: POST /v1/envelopes/{id}/review.",
              "tenant_read": "The `tenant_read` permission. Operations: GET /v1/alerts, GET /v1/audit, GET /v1/gateways, GET /v1/keys, GET /v1/quarantine.",
              "trace_read": "The `trace_read` permission. Operations: GET /v1/fsma.csv, GET /v1/lots/{lot}/epcis, GET /v1/lots/{lot}/events, GET /v1/lots/{lot}/fsma.csv.",
              "webhook_admin": "The `webhook_admin` permission. Operations: GET /v1/webhooks, GET /v1/webhooks/{id}, GET /v1/webhooks/{id}/deliveries, PATCH /v1/webhooks/{id}, POST /v1/webhooks, POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver, POST /v1/webhooks/{id}/rotate-secret."
            }
          }
        }
      },
      "broker": {
        "type": "http",
        "scheme": "bearer",
        "description": "The EMQX shared broker secret."
      },
      "deviceMtls": {
        "type": "mutualTLS",
        "description": "Device or gateway client certificate. Ingest additionally requires a signed envelope."
      }
    },
    "headers": {
      "X-Request-Id": {
        "description": "Request id: the caller's `X-Request-Id` when it is 1 to 64 of A-Z a-z 0-9 . _ -, otherwise a generated one.",
        "schema": {
          "type": "string"
        }
      },
      "Retry-After": {
        "description": "Seconds to wait before retrying.",
        "schema": {
          "type": "string"
        }
      },
      "Allow": {
        "description": "Comma-separated methods the path accepts.",
        "schema": {
          "type": "string"
        }
      },
      "Set-Cookie": {
        "description": "The session cookie (`__Host-agt_sid`; `agt_sid` in insecure dev mode): Path=/, HttpOnly, SameSite=Lax, Max-Age, and Secure unless insecure cookies are on. Logout sends Max-Age=0 with an empty value.",
        "schema": {
          "type": "string"
        }
      },
      "Cache-Control": {
        "description": "`no-store` on session responses.",
        "schema": {
          "type": "string"
        }
      },
      "Idempotent-Replayed": {
        "description": "`true` when the response is the stored response of an earlier request with the same Idempotency-Key.",
        "schema": {
          "type": "string",
          "enum": [
            "true"
          ]
        }
      }
    },
    "responses": {
      "BadRequestId": {
        "description": "The X-Request-Id header is present and malformed.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "bad request id",
              "code": "bad_request_id"
            }
          }
        }
      },
      "PayloadTooLarge": {
        "description": "The request body is over 1 MiB.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "body too large",
              "code": "body_too_large"
            }
          }
        }
      },
      "MethodNotAllowed": {
        "description": "The path exists but not for this method. `Allow` lists the methods it accepts.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          },
          "Allow": {
            "$ref": "#/components/headers/Allow"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "method not allowed",
              "code": "method_not_allowed"
            }
          }
        }
      },
      "InternalError": {
        "description": "Unexpected failure; the detail is only in the server log.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "internal error",
              "code": "internal_error"
            }
          }
        }
      },
      "BadRequestIdOrIdempotencyKey": {
        "description": "The X-Request-Id header is present and malformed, or the Idempotency-Key header is malformed or repeated.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "bad_request_id": {
                "value": {
                  "error": "bad request id",
                  "code": "bad_request_id"
                }
              },
              "invalid_idempotency_key": {
                "value": {
                  "error": "invalid idempotency key: one header of 1 to 255 visible ASCII characters",
                  "code": "invalid_idempotency_key"
                }
              }
            }
          }
        }
      },
      "IdempotencyKeyConflict": {
        "description": "The Idempotency-Key's first request is still running (retry after `Retry-After` seconds), or it ran but its response cannot be replayed (too large to store, or never recorded).",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          },
          "Retry-After": {
            "$ref": "#/components/headers/Retry-After"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "idempotency_key_in_use": {
                "value": {
                  "error": "idempotency key in use: retry later",
                  "code": "idempotency_key_in_use"
                }
              },
              "idempotency_key_used": {
                "value": {
                  "error": "idempotency key used: the response is too large to replay",
                  "code": "idempotency_key_used"
                }
              },
              "idempotency_key_unrecorded": {
                "value": {
                  "error": "idempotency key used: the request ran but its response was not recorded",
                  "code": "idempotency_key_used"
                }
              }
            }
          }
        }
      },
      "IdempotencyKeyMismatch": {
        "description": "The Idempotency-Key was used by this principal within 24 hours with another method, path, query or body.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "idempotency key mismatch: the key was used with another request",
              "code": "idempotency_key_mismatch"
            }
          }
        }
      },
      "LotRemoved": {
        "description": "The record was deleted when its retention period ended (#209): the code named a lot, or a fruit or carton of a lot, of a company that left CropPath. Only the code and the date it was removed are kept, so the answer says nothing else about the lot; every such code gets this same body and headers, and the code is never echoed. A code that never named a record stays 404.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/X-Request-Id"
          },
          "Cache-Control": {
            "description": "`public, max-age=0, s-maxage=60`, as a 404. Never `Set-Cookie`.",
            "schema": {
              "type": "string"
            }
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "error": "lot removed: this record is no longer available",
              "code": "lot_removed"
            }
          }
        }
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": [
          "error",
          "code"
        ],
        "additionalProperties": false,
        "description": "Every error body. `code` is the message head reduced to lower-case snake case.",
        "properties": {
          "error": {
            "type": "string"
          },
          "code": {
            "type": "string"
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BatchItemError"
            },
            "description": "A batch request (#170) only: the items that failed, by index. Every invalid item on a 400 `invalid_batch`; the one item the stored state refused on a `batch_rejected`, with the status the single-item route gives it."
          },
          "details": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AddressToCode"
            },
            "maxItems": 3,
            "description": "A seal refused with `address_not_coded` (#273, owner decision D5) only: each record whose address must be picked from the official list of administrative units (a province and a commune) before the lot can be packed.",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "error": "no such route",
          "code": "no_such_route"
        }
      },
      "AddressToCode": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "kind",
          "code"
        ],
        "description": "A record whose address is not coded by official administrative unit codes yet (#273, D5): the lot's packing house (`facility`), its growing area (`growing_area`) or the company profile (`company_profile`, in Viet Nam; `code` null, a company has one).",
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "facility",
              "growing_area",
              "company_profile"
            ]
          },
          "code": {
            "type": [
              "string",
              "null"
            ],
            "description": "The facility or growing-area code; null for the company profile."
          }
        },
        "x-not-in-sdk": true
      },
      "User": {
        "type": "object",
        "required": [
          "id",
          "email",
          "display_name"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer"
          },
          "email": {
            "type": "string"
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "id": 1,
          "email": "alice@coop.example",
          "display_name": "Alice"
        }
      },
      "Membership": {
        "type": "object",
        "required": [
          "tenant",
          "role",
          "facilities",
          "lab_id"
        ],
        "additionalProperties": false,
        "properties": {
          "tenant": {
            "type": "string"
          },
          "role": {
            "type": "string",
            "description": "e.g. tenant_admin, platform_admin, operator, lab, auditor."
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "null means every facility of the tenant."
          },
          "lab_id": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "tenant": "coop-dl",
          "role": "tenant_admin",
          "facilities": null,
          "lab_id": null
        }
      },
      "LoginRequest": {
        "type": "object",
        "required": [
          "email",
          "password"
        ],
        "properties": {
          "email": {
            "type": "string",
            "minLength": 1
          },
          "password": {
            "type": "string",
            "minLength": 1
          }
        },
        "example": {
          "email": "alice@coop.example",
          "password": "correct horse battery"
        }
      },
      "AuthSession": {
        "type": "object",
        "required": [
          "user",
          "memberships",
          "csrf_token"
        ],
        "additionalProperties": false,
        "properties": {
          "user": {
            "$ref": "#/components/schemas/User"
          },
          "memberships": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Membership"
            }
          },
          "csrf_token": {
            "type": "string"
          },
          "two_factor": {
            "$ref": "#/components/schemas/TwoFactorState"
          }
        },
        "example": {
          "user": {
            "id": 1,
            "email": "alice@coop.example",
            "display_name": "Alice"
          },
          "memberships": [
            {
              "tenant": "coop-dl",
              "role": "tenant_admin",
              "facilities": null,
              "lab_id": null
            }
          ],
          "csrf_token": "q3Vb0mXl2sQ"
        }
      },
      "Me": {
        "type": "object",
        "required": [
          "user",
          "memberships",
          "csrf_token",
          "tenant",
          "roles"
        ],
        "additionalProperties": false,
        "properties": {
          "user": {
            "$ref": "#/components/schemas/User"
          },
          "memberships": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Membership"
            }
          },
          "csrf_token": {
            "type": "string"
          },
          "tenant": {
            "type": [
              "string",
              "null"
            ],
            "description": "Tenant the request acts for; null when the user has no membership."
          },
          "roles": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "tenant_name": {
            "type": [
              "string",
              "null"
            ],
            "description": "#282 (always present in this answer): the name of the tenant the request acts for (`tenant`), for the console's top bar; null when that company has no registered name (for example a platform admin acting for a company id that is not registered), and the console then shows `tenant`.",
            "x-not-in-sdk": true
          },
          "lab_name": {
            "type": [
              "string",
              "null"
            ],
            "description": "#282 (always present in this answer): for a lab user (`roles` holds `lab`), the name of its lab (the membership's `lab_id`); null otherwise.",
            "x-not-in-sdk": true
          },
          "two_factor": {
            "$ref": "#/components/schemas/TwoFactorState"
          }
        },
        "example": {
          "user": {
            "id": 1,
            "email": "alice@coop.example",
            "display_name": "Alice"
          },
          "memberships": [
            {
              "tenant": "coop-dl",
              "role": "tenant_admin",
              "facilities": null,
              "lab_id": null
            }
          ],
          "csrf_token": "q3Vb0mXl2sQ",
          "tenant": "coop-dl",
          "roles": [
            "tenant_admin"
          ],
          "tenant_name": "Dak Lak durian co-op",
          "lab_name": null
        },
        "x-sdk-example": {
          "user": {
            "id": 1,
            "email": "alice@coop.example",
            "display_name": "Alice"
          },
          "memberships": [
            {
              "tenant": "coop-dl",
              "role": "tenant_admin",
              "facilities": null,
              "lab_id": null
            }
          ],
          "csrf_token": "q3Vb0mXl2sQ",
          "tenant": "coop-dl",
          "roles": [
            "tenant_admin"
          ]
        }
      },
      "PasswordChangeRequest": {
        "type": "object",
        "required": [
          "current_password",
          "new_password"
        ],
        "properties": {
          "current_password": {
            "type": "string"
          },
          "new_password": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "description": "#187: the 6-digit code from the authenticator app; required (or `backup_code`) when the account has two-step sign-in."
          },
          "backup_code": {
            "type": "string",
            "description": "#187: one unused backup code, instead of `code`."
          }
        },
        "example": {
          "current_password": "correct horse battery",
          "new_password": "another long passphrase"
        }
      },
      "PasswordChanged": {
        "type": "object",
        "required": [
          "csrf_token"
        ],
        "additionalProperties": false,
        "properties": {
          "csrf_token": {
            "type": "string"
          }
        },
        "example": {
          "csrf_token": "Zk1pQ8w2Ls"
        }
      },
      "ReauthRequest": {
        "type": "object",
        "required": [
          "password"
        ],
        "properties": {
          "password": {
            "type": "string",
            "minLength": 1
          },
          "code": {
            "type": "string",
            "description": "SELF-1-6 (#187): the 6-digit code from the authenticator app; required (or `backup_code`) when the account has two-step sign-in."
          },
          "backup_code": {
            "type": "string",
            "description": "SELF-1-6 (#187): one unused backup code, instead of `code`."
          }
        },
        "example": {
          "password": "correct horse battery"
        }
      },
      "Health": {
        "type": "object",
        "required": [
          "ok",
          "outbound_backlog",
          "certificates"
        ],
        "properties": {
          "ok": {
            "const": true
          },
          "outbound_backlog": {
            "type": "object",
            "additionalProperties": {
              "type": "integer"
            },
            "description": "Undelivered outbound items per target."
          },
          "certificates": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CertificateStatus"
            }
          },
          "read_only": {
            "const": true,
            "description": "Present (true) only in the read-only maintenance mode of the PostgreSQL cutover (AGRITRACE_READ_ONLY=1, #123): every request but GET, and every audited read (the exports), then answers 503 with Retry-After, and `warnings` says so."
          },
          "mqtt": {
            "type": "object",
            "description": "Present when the MQTT bridge runs.",
            "required": [
              "broker",
              "connected"
            ],
            "properties": {
              "broker": {
                "type": "string"
              },
              "connected": {
                "type": "boolean"
              },
              "error": {
                "type": "string"
              },
              "subscribed": {
                "type": "boolean",
                "description": "true once connected and the broker granted every uplink subscription of the bridge. While false the bridge retries each refused subscription with a backoff (1 s doubling to 60 s), and `warnings` says so (#254)."
              },
              "missing_filters": {
                "type": "integer",
                "minimum": 0,
                "description": "Uplink subscriptions not granted (yet) on the current connection; all of them while not connected."
              }
            }
          },
          "warnings": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Present when a certificate is expired or due, MQTT is not connected, or the broker has not granted every uplink subscription of the MQTT bridge."
          }
        },
        "example": {
          "ok": true,
          "outbound_backlog": {
            "national": 0
          },
          "certificates": []
        }
      },
      "CertificateStatus": {
        "type": "object",
        "required": [
          "path",
          "subject",
          "not_after",
          "remaining_s",
          "remaining_fraction",
          "expired"
        ],
        "properties": {
          "path": {
            "type": "string"
          },
          "subject": {
            "type": "string"
          },
          "not_after": {
            "type": "string",
            "format": "date-time"
          },
          "remaining_s": {
            "type": "integer"
          },
          "remaining_fraction": {
            "type": "number"
          },
          "expired": {
            "type": "boolean"
          }
        },
        "example": {
          "path": "/certs/gw-01.pem",
          "subject": "gw-01",
          "not_after": "2027-01-01T00:00:00+00:00",
          "remaining_s": 7776000,
          "remaining_fraction": 0.5,
          "expired": false
        }
      },
      "BrokerAuthzRequest": {
        "type": "object",
        "description": "Missing fields are treated as empty strings (and denied).",
        "properties": {
          "username": {
            "type": "string"
          },
          "action": {
            "type": "string"
          },
          "topic": {
            "type": "string"
          }
        },
        "example": {
          "username": "knk-1",
          "action": "publish",
          "topic": "agritrace/v1/coop-dl/ph1/knk-1/event"
        }
      },
      "BrokerAuthzResult": {
        "type": "object",
        "required": [
          "result"
        ],
        "additionalProperties": false,
        "properties": {
          "result": {
            "enum": [
              "allow",
              "deny"
            ]
          }
        },
        "example": {
          "result": "deny"
        }
      },
      "Envelope": {
        "type": "object",
        "additionalProperties": true,
        "description": "A signed envelope (envelope version 1, `spec` `agritrace.iot/1.0`). The server applies the envelope's full schema, served at /developers/downloads/envelope-v1.schema.json; it is deliberately not duplicated here, so this schema is open. An `event` envelope's `eventType` and the context keys it requires are those of /developers/downloads/event-types-v1.json; each reading's `capability`, unit and range are those of /developers/downloads/capabilities-v1.json; `device.profile` is `<profile id>@<profile version>` of a device profile below /developers/downloads/profiles/ (see `DeviceCreate.profile`).",
        "example": {
          "spec": "agritrace.iot/1.0",
          "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
          "kind": "event",
          "eventType": "inspect",
          "device": {
            "id": "knk-1",
            "profile": "vn.agritrace.durian-knocker@1.0.0",
            "gateway": "gw-01"
          },
          "time": "2026-09-30T08:00:00.000+07:00",
          "seq": 0,
          "context": {
            "lot": "LOT-A",
            "facility": "66-DL-SR-0001-CHN"
          },
          "readings": [
            {
              "capability": "produce.maturity_index",
              "value": 82.0,
              "unit": "%"
            }
          ]
        }
      },
      "StoredEnvelope": {
        "type": "object",
        "additionalProperties": true,
        "required": [
          "_status"
        ],
        "description": "A stored envelope (envelope version 1, see `Envelope`: its schema is served at /developers/downloads/envelope-v1.schema.json, its event types at /developers/downloads/event-types-v1.json; open here) plus the server-added `_status`.",
        "properties": {
          "_status": {
            "type": "string"
          }
        },
        "example": {
          "spec": "agritrace.iot/1.0",
          "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
          "kind": "event",
          "eventType": "inspect",
          "device": {
            "id": "knk-1",
            "profile": "vn.agritrace.durian-knocker@1.0.0",
            "gateway": "gw-01"
          },
          "time": "2026-09-30T08:00:00.000+07:00",
          "seq": 0,
          "context": {
            "lot": "LOT-A",
            "facility": "66-DL-SR-0001-CHN"
          },
          "readings": [
            {
              "capability": "produce.maturity_index",
              "value": 82.0,
              "unit": "%"
            }
          ],
          "_status": "accepted"
        }
      },
      "IngestResult": {
        "type": "object",
        "required": [
          "status",
          "id",
          "reasons"
        ],
        "additionalProperties": false,
        "properties": {
          "status": {
            "enum": [
              "accepted",
              "quarantined",
              "duplicate",
              "rejected"
            ]
          },
          "id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Envelope id; null when the body could not be parsed far enough to read it."
          },
          "reasons": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Quarantine reasons, or the single rejection reason."
          }
        },
        "example": {
          "status": "accepted",
          "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
          "reasons": []
        }
      },
      "EpcisDocument": {
        "type": "object",
        "additionalProperties": true,
        "description": "An EPCIS 2.0 JSON-LD document; its shape is defined by the EPCIS standard, so the schema is open.",
        "example": {
          "@context": [
            "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld"
          ],
          "type": "EPCISDocument"
        }
      },
      "Alert": {
        "type": "object",
        "required": [
          "id",
          "tenant",
          "kind",
          "severity",
          "device_id",
          "envelope_id",
          "detail",
          "created_at",
          "resolved_at"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer"
          },
          "tenant": {
            "type": [
              "string",
              "null"
            ]
          },
          "kind": {
            "type": "string"
          },
          "severity": {
            "type": "string"
          },
          "device_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "envelope_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "detail": {
            "type": "object",
            "additionalProperties": true,
            "description": "Shape depends on `kind` (for example `reasons`, or `from` and `to` for a sequence gap)."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "resolved_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null while open."
          }
        },
        "example": {
          "id": 7,
          "tenant": "coop-dl",
          "kind": "seq_gap",
          "severity": "warning",
          "device_id": "scale-1",
          "envelope_id": null,
          "detail": {
            "from": 4,
            "to": 6
          },
          "created_at": 1790000000.5,
          "resolved_at": null
        }
      },
      "QuarantinedEnvelope": {
        "type": "object",
        "required": [
          "id",
          "device_id",
          "seq",
          "kind",
          "event_type",
          "event_time",
          "lot",
          "growing_area",
          "reasons"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "device_id": {
            "type": "string"
          },
          "seq": {
            "type": "integer"
          },
          "kind": {
            "type": "string"
          },
          "event_type": {
            "type": [
              "string",
              "null"
            ]
          },
          "event_time": {
            "type": "string"
          },
          "lot": {
            "type": [
              "string",
              "null"
            ]
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ]
          },
          "reasons": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "example": {
          "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
          "device_id": "scale-1",
          "seq": 3,
          "kind": "event",
          "event_type": "receive",
          "event_time": "2026-09-30T08:00:00.000+07:00",
          "lot": "LOT-A",
          "growing_area": "VN-DL-SR-0123",
          "reasons": [
            "volume_exceeds_cap"
          ]
        }
      },
      "Volume": {
        "type": "object",
        "required": [
          "growing_area",
          "season",
          "declared_kg",
          "cap_kg"
        ],
        "additionalProperties": false,
        "properties": {
          "growing_area": {
            "type": "string"
          },
          "season": {
            "type": "string"
          },
          "declared_kg": {
            "type": "number"
          },
          "cap_kg": {
            "type": [
              "number",
              "null"
            ],
            "description": "area_ha times yield_kg_per_ha; null when the growing area is unknown or is a tenant-created area not yet approved by a platform admin."
          }
        },
        "example": {
          "growing_area": "VN-DL-SR-0123",
          "season": "2026",
          "declared_kg": 1200.5,
          "cap_kg": 20000.0
        }
      },
      "ReviewRequest": {
        "type": "object",
        "required": [
          "decision"
        ],
        "properties": {
          "decision": {
            "enum": [
              "approve",
              "reject"
            ]
          },
          "note": {
            "type": "string",
            "description": "Optional; recorded with the review."
          }
        },
        "example": {
          "decision": "reject",
          "note": "scale was not calibrated"
        }
      },
      "ReviewResult": {
        "type": "object",
        "required": [
          "id",
          "status"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "status": {
            "enum": [
              "accepted",
              "rejected_after_review"
            ]
          }
        },
        "example": {
          "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
          "status": "rejected_after_review"
        }
      },
      "CommandRequest": {
        "type": "object",
        "required": [
          "name"
        ],
        "properties": {
          "name": {
            "type": "string"
          },
          "params": {
            "type": "object",
            "additionalProperties": true,
            "description": "Defaults to an empty object."
          }
        },
        "example": {
          "name": "calibrate",
          "params": {}
        }
      },
      "CommandIssued": {
        "type": "object",
        "required": [
          "id"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          }
        },
        "example": {
          "id": "6f1c1c52-62a0-4f0e-8c3a-0b7e8d6d3e10"
        }
      },
      "Command": {
        "type": "object",
        "required": [
          "id",
          "tenant",
          "site",
          "device_id",
          "name",
          "params",
          "issued_by",
          "issued_at",
          "status",
          "result",
          "completed_at"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "site": {
            "type": "string"
          },
          "device_id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "params": {
            "type": "object",
            "additionalProperties": true
          },
          "issued_by": {
            "type": "string"
          },
          "issued_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "status": {
            "enum": [
              "pending",
              "sent",
              "succeeded",
              "failed",
              "accepted",
              "rejected",
              "completed",
              "aborted",
              "expired"
            ],
            "x-sdk-enum": [
              "pending",
              "sent",
              "succeeded",
              "failed"
            ]
          },
          "result": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true,
            "description": "The device reply or the dispatch error; null until settled."
          },
          "completed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null until settled."
          },
          "kind": {
            "enum": [
              "config",
              "actuation"
            ],
            "description": "#242, with getCommand or listDeviceCommands `channel=1` only: `config` (set_model, calibrate, ...: status pending, sent, then succeeded or failed) or `actuation` (an irrigation controller's run_zone or set_program, a signed command document the controller checks and enforces locally: status pending, sent, then accepted and completed or aborted, or rejected; expired when it was not delivered or accepted before `expires_at`, or no final report came; failed when the dispatch failed). Without `channel=1` the status of an actuation command is still answered.",
            "x-not-in-sdk": true
          },
          "expires_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "#242, with getCommand or listDeviceCommands `channel=1` only: Unix seconds after which the controller refuses the command (null for a config command).",
            "x-not-in-sdk": true
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "#242, with getCommand or listDeviceCommands `channel=1` only: why an actuation command was rejected, aborted or expired, as the controller or the server said it (for example `bad_sig`, `expired`, `wrong_device`, `replayed`, `limit_exceeded`, `interlock`, `manual_override_active`, `clock_unsynced`, `no_final_report`); null otherwise.",
            "x-not-in-sdk": true
          },
          "accepted_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "#242, with getCommand or listDeviceCommands `channel=1` only: Unix seconds when the controller accepted the actuation command; null until then and for a config command.",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "id": "6f1c1c52-62a0-4f0e-8c3a-0b7e8d6d3e10",
          "tenant": "coop-dl",
          "site": "ph1",
          "device_id": "knk-1",
          "name": "set_model",
          "params": {
            "version": "m9"
          },
          "issued_by": "legacy-user",
          "issued_at": 1790000000.5,
          "status": "succeeded",
          "result": {
            "ok": true
          },
          "completed_at": 1790000003.0
        }
      },
      "CommandKey": {
        "type": "object",
        "required": [
          "kid",
          "alg",
          "jwk"
        ],
        "additionalProperties": false,
        "description": "#242: one platform command key's public part.",
        "properties": {
          "kid": {
            "type": "string",
            "pattern": "^platform-cmd-[0-9a-f]{16}$",
            "description": "`platform-cmd-` and the first 16 hex digits of the SHA-256 of the public key's SubjectPublicKeyInfo DER."
          },
          "alg": {
            "const": "ES256"
          },
          "jwk": {
            "type": "object",
            "required": [
              "kty",
              "crv",
              "x",
              "y"
            ],
            "additionalProperties": false,
            "description": "The public key as an RFC 7517 JWK.",
            "properties": {
              "kty": {
                "const": "EC"
              },
              "crv": {
                "const": "P-256"
              },
              "x": {
                "type": "string"
              },
              "y": {
                "type": "string"
              }
            }
          }
        },
        "x-not-in-sdk": true
      },
      "CommandKeys": {
        "type": "object",
        "required": [
          "keys"
        ],
        "additionalProperties": false,
        "properties": {
          "keys": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CommandKey"
            },
            "description": "Empty when the server has no command key."
          }
        },
        "x-not-in-sdk": true
      },
      "AuditEntry": {
        "type": "object",
        "description": "One append-only audit row. No column ever holds a password, a session, API or CSRF token, a cookie or a raw IP address.",
        "required": [
          "id",
          "at",
          "actor",
          "tenant",
          "action",
          "entity",
          "entity_id",
          "before_hash",
          "after",
          "request_id",
          "ip_hash",
          "actor_kind",
          "actor_name"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer",
            "description": "Increasing row id; the list is ordered by it, newest first."
          },
          "at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "actor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The principal's user (email, `token:<name>` or legacy user); null for a failed login."
          },
          "tenant": {
            "type": [
              "string",
              "null"
            ]
          },
          "action": {
            "type": "string",
            "description": "For example `auth.login`, `auth.logout`, `auth.password.change`, `envelope.review` or `device.command.issue`; `.failed` is appended when the request answered 400 or more."
          },
          "entity": {
            "type": "string",
            "description": "`user`, `session`, `envelope` or `device`."
          },
          "entity_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The record's id; for a failed login an HMAC of the normalized email, never the email."
          },
          "before_hash": {
            "type": [
              "string",
              "null"
            ],
            "description": "SHA-256 hex of the canonical JSON (sorted keys, compact) of the changed fields' prior state; null when no existing record changed or the request failed."
          },
          "after": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true,
            "properties": {
              "status": {
                "type": "integer"
              },
              "error": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "description": "Outcome: the HTTP status, plus the error code on failure or a short summary on success. A row the server's command line (`cli:*`) wrote before #188 has no `status`; newer ones carry the status the API would have answered (201 for a create, 200 otherwise)."
          },
          "request_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The request's X-Request-Id."
          },
          "ip_hash": {
            "type": [
              "string",
              "null"
            ],
            "description": "HMAC-SHA256 of the client IP."
          },
          "actor_kind": {
            "type": "string",
            "enum": [
              "member",
              "support",
              "api_token",
              "api_client",
              "server",
              "other"
            ],
            "description": "Who the actor is (SELF-1-7, #188): `member` a signed-in user of the company (by email), `support` CropPath staff (a platform admin) acting for the company, `api_token` an API token (`token:<name>`), `api_client` an API client (`oauth:<client_id>`), `server` the server's command line (`cli:*`), `other` anything else (a configured token, or no actor)."
          },
          "actor_name": {
            "type": [
              "string",
              "null"
            ],
            "description": "A member's current display name, an API token's name or the API client's name; null when there is none (support staff are named by their email in `actor`)."
          }
        },
        "example": {
          "id": 42,
          "at": 1790000000.5,
          "actor": "admin@coop.example",
          "tenant": "coop-dl",
          "action": "envelope.review",
          "entity": "envelope",
          "entity_id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
          "before_hash": "9b0f1d6a2c7e4b3f8a5d0c9e1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c",
          "after": {
            "status": 200,
            "id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
            "decision": "approve",
            "result": "accepted"
          },
          "request_id": "req-7f3a",
          "ip_hash": "c3a1e07d94b2f58a61d0e7c4b9f3a2d8e5c17b60f4a9d2e3b8c5f1a7d0e4b962",
          "actor_kind": "member",
          "actor_name": "Nguyễn Văn An"
        }
      },
      "AuditPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AuditEntry"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next (older) page; null on the last page."
          }
        }
      },
      "Facility": {
        "type": "object",
        "required": [
          "code",
          "tenant",
          "name",
          "address",
          "province",
          "district",
          "gacc_phc_code",
          "lines",
          "source",
          "approved_at",
          "slug",
          "created_at",
          "updated_at",
          "proposed_at"
        ],
        "additionalProperties": false,
        "description": "A facility (packing house) of one tenant. Codes created through the API look like VN-TGPH-021; codes from the migration backfill keep their original spelling.",
        "properties": {
          "code": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "address": {
            "type": [
              "string",
              "null"
            ]
          },
          "province": {
            "type": [
              "string",
              "null"
            ]
          },
          "district": {
            "type": [
              "string",
              "null"
            ]
          },
          "gacc_phc_code": {
            "type": [
              "string",
              "null"
            ],
            "description": "GACC registration of the packing house."
          },
          "lines": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "source": {
            "enum": [
              "manual",
              "backfill"
            ]
          },
          "approved_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null until approved."
          },
          "slug": {
            "type": "string"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "proposed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "SELF-2-8 (#197): Unix seconds when a company admin proposed the facility (POST /v1/facility-proposals); null for a facility the platform created. A proposal with approved_at null waits for CropPath: no lot, shipment, device, gateway, harvest app key or signing key may name it."
          },
          "commune": {
            "description": "The commune's official name (xã, phường or đặc khu) when the record is coded; else null. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "x-not-in-sdk": true
          },
          "province_code": {
            "description": "The province's official 2-digit code, in the list `admin_units_version`; null when not coded. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "The commune's official 5-digit code, in the list `admin_units_version`; null when not coded. A code is only meaningful with its version (codes were reused across the 2025 reform). Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "admin_units_version": {
            "description": "The version of the official list the codes were taken from (for example `vn-2026-10-17`); null without codes. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^vn-[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "address_before_reform": {
            "description": "The province, district and commune text the record held before it was coded, or the text a request gave through the deprecated text path; kept for good once set. Null for a record entered with codes. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "province",
              "district",
              "commune"
            ],
            "properties": {
              "province": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "district": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "commune": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "x-not-in-sdk": true
          },
          "address_status": {
            "description": "`coded`: the codes are set from the official list; `choose_commune`: the old commune was split, a person picks one of `address_candidates`; `needs_commune`: no codes yet (given as text, or before the reform), a person picks the commune; `outside_vietnam`: a company profile in another country, where the codes do not apply. Null for a record not reviewed since the codes were introduced. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "coded",
              "choose_commune",
              "needs_commune",
              "outside_vietnam",
              null
            ],
            "x-not-in-sdk": true
          },
          "address_candidates": {
            "description": "For `choose_commune`: the official commune codes to pick from; else null. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string",
              "pattern": "^[0-9]{5}$"
            },
            "x-not-in-sdk": true
          }
        },
        "example": {
          "code": "VN-TGPH-021",
          "tenant": "coop-dl",
          "name": "Tan Phu packing house",
          "address": "Cai Lay, Tien Giang",
          "province": "Tien Giang",
          "district": "Cai Lay",
          "gacc_phc_code": "VNPH-TG-021",
          "lines": [
            "L1",
            "L2"
          ],
          "source": "manual",
          "approved_at": null,
          "slug": "vn-tgph-021",
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5,
          "proposed_at": null
        }
      },
      "FacilityPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Facility"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "FacilityCreate": {
        "type": "object",
        "required": [
          "code",
          "name"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z]{2}-[A-Z0-9]{2,8}-[0-9A-Z]{2,12}$"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "address": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 300
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: the province as free text. Send `province_code` and `commune_code` instead. A body that gives the address as text only is still accepted until the sunset: the record is stored as not yet coded (`address_status` `needs_commune`) and the answer carries the `Deprecation`, `Sunset` and `Link` headers.",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: Viet Nam has had no district level since 1 July 2025. Send `province_code` and `commune_code` instead; with them `district` must be absent or null (400 `district_with_codes`).",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "province_code": {
            "description": "#273: the province (tỉnh or thành phố trực thuộc trung ương) by its official 2-digit code in the administrative units list in force (`getAdminUnits`). Sent with `commune_code`, both or neither; with them `province`, `district` and `commune` must be absent or null and the server writes the official names.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "#273: the commune (xã, phường or đặc khu) by its official 5-digit code in the administrative units list in force (`getAdminUnits` with `province`). Sent with `province_code`, both or neither; the commune must lie in that province by the list, never by its digits.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "gacc_phc_code": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64
          },
          "lines": {
            "type": "array",
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "minLength": 1,
              "maxLength": 32
            }
          },
          "slug": {
            "type": "string",
            "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
            "maxLength": 64
          }
        },
        "example": {
          "code": "VN-TGPH-021",
          "name": "Tan Phu packing house"
        }
      },
      "FacilityUpdate": {
        "type": "object",
        "minProperties": 1,
        "additionalProperties": false,
        "description": "gacc_phc_code and slug: platform_admin only.",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "address": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 300
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: the province as free text. Send `province_code` and `commune_code` instead. A body that gives the address as text only is still accepted until the sunset: the record is stored as not yet coded (`address_status` `needs_commune`) and the answer carries the `Deprecation`, `Sunset` and `Link` headers.",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: Viet Nam has had no district level since 1 July 2025. Send `province_code` and `commune_code` instead; with them `district` must be absent or null (400 `district_with_codes`).",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "province_code": {
            "description": "#273: the province (tỉnh or thành phố trực thuộc trung ương) by its official 2-digit code in the administrative units list in force (`getAdminUnits`). Sent with `commune_code`, both or neither; with them `province`, `district` and `commune` must be absent or null and the server writes the official names.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "#273: the commune (xã, phường or đặc khu) by its official 5-digit code in the administrative units list in force (`getAdminUnits` with `province`). Sent with `province_code`, both or neither; the commune must lie in that province by the list, never by its digits.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "gacc_phc_code": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64
          },
          "lines": {
            "type": "array",
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "minLength": 1,
              "maxLength": 32
            }
          },
          "slug": {
            "type": "string",
            "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
            "maxLength": 64
          }
        },
        "example": {
          "address": "Cai Lay, Tien Giang"
        }
      },
      "Tenant": {
        "type": "object",
        "required": [
          "id",
          "name",
          "source",
          "created_at",
          "members",
          "admins",
          "offboarding"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "source": {
            "enum": [
              "manual",
              "backfill"
            ]
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "members": {
            "type": "integer",
            "minimum": 0,
            "description": "SELF-1-3 (#184): how many people hold an active membership of the tenant (each counted once); SELF-1-4 (#185): a membership the company turned off does not count."
          },
          "admins": {
            "type": "integer",
            "minimum": 0,
            "description": "SELF-1-3 (#184): how many of them are active company admins whose account is active (SELF-1-4, #185)."
          },
          "offboarding": {
            "$ref": "#/components/schemas/CompanyOffboarding",
            "description": "SELF-2-4 (#193): whether the company is leaving CropPath."
          },
          "platform": {
            "type": "boolean",
            "description": "#282: present only with listTenants `platform=1`. true for a company that can never be marked as leaving CropPath: the company of CropPath's platform admins (it holds a platform admin's membership; startCompanyOffboarding answers 409 `platform company`) and (#283) the company record of CropPath's lab logins (`croppath-labs`; 409 `lab logins company`).",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "id": "coop-dl",
          "name": "Dak Lak durian co-op",
          "source": "manual",
          "created_at": 1790000000.5,
          "members": 12,
          "admins": 2,
          "offboarding": {
            "status": "active",
            "retention_years": null,
            "started_at": null,
            "window_ends_at": null,
            "left_at": null,
            "retention_ends_at": null,
            "steps_done": 0
          }
        }
      },
      "TenantPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Tenant"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "TenantCreate": {
        "type": "object",
        "required": [
          "id",
          "name"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^[a-z0-9][a-z0-9-]{1,63}$"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          }
        },
        "example": {
          "id": "coop-dl",
          "name": "Dak Lak durian co-op"
        }
      },
      "Device": {
        "type": "object",
        "description": "A device and its status read model. `last_seen`, `max_seq` and `last_model` come from the device's ingest state (null before its first message); `firmware` is `device.fw` of its newest stored envelope that carries one, and `battery_pct` / `battery_v` the newest `device.battery` / `device.battery_voltage` reading of a status or event envelope, each among its latest 32 stored (accepted or quarantined) envelopes; `last_calibrated_at` is when its latest succeeded `calibrate` command completed. `ready` is true when the device is active, has an active key that may sign for it (its own, or one of an active gateway at its tenant and site) and was last seen within 24 hours.",
        "required": [
          "device_id",
          "tenant",
          "site",
          "facility",
          "profile",
          "status",
          "display_name",
          "vendor_model",
          "serial",
          "created_at",
          "commands",
          "last_seen",
          "max_seq",
          "last_model",
          "firmware",
          "battery_pct",
          "battery_v",
          "last_calibrated_at",
          "ready",
          "approval",
          "approval_reason",
          "approval_at"
        ],
        "additionalProperties": false,
        "properties": {
          "device_id": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "site": {
            "type": "string",
            "description": "The site segment of the device's ingest route and MQTT topics."
          },
          "facility": {
            "type": [
              "string",
              "null"
            ],
            "description": "Facility code; null for a device registered before facilities, whose site then stands in for the facility in operator scope."
          },
          "profile": {
            "type": "string",
            "description": "Device profile id (without version)."
          },
          "status": {
            "type": "string",
            "description": "Only `active` devices are accepted by ingest and the broker."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "vendor_model": {
            "type": [
              "string",
              "null"
            ]
          },
          "serial": {
            "type": [
              "string",
              "null"
            ]
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "commands": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "The downlink commands the device's profile declares, sorted by name: the only names `POST /v1/devices/{id}/commands` accepts for this device (a facility-scoped operator may issue `calibrate` only)."
          },
          "last_seen": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds (server time of the last message)."
          },
          "max_seq": {
            "type": [
              "integer",
              "null"
            ]
          },
          "last_model": {
            "type": [
              "string",
              "null"
            ]
          },
          "firmware": {
            "type": [
              "string",
              "null"
            ]
          },
          "battery_pct": {
            "type": [
              "number",
              "null"
            ]
          },
          "battery_v": {
            "type": [
              "number",
              "null"
            ]
          },
          "last_calibrated_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "ready": {
            "type": "boolean"
          },
          "approval": {
            "type": "string",
            "enum": [
              "pending",
              "approved",
              "rejected"
            ],
            "description": "Platform approval (#201): `pending` until a platform admin approves or rejects it. Only evidence from an approved device, signed by its own key or an approved gateway's, counts as Device-recorded or above; evidence from a pending or rejected one is stored and counts as Self-declared."
          },
          "approval_reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "The reason of a rejection; null otherwise."
          },
          "approval_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the last approval decision."
          }
        },
        "example": {
          "device_id": "knk-1",
          "tenant": "coop-dl",
          "site": "ph1",
          "facility": "VN-TGPH-021",
          "profile": "vn.agritrace.durian-knocker",
          "status": "active",
          "display_name": "Knocker line 1",
          "vendor_model": "SF-100",
          "serial": "SF100-000123",
          "created_at": 1790000000.5,
          "commands": [
            "calibrate",
            "set_model",
            "set_session"
          ],
          "last_seen": 1790003600.25,
          "max_seq": 412,
          "last_model": "m1",
          "firmware": "1.4.2",
          "battery_pct": 87.0,
          "battery_v": 3.92,
          "last_calibrated_at": 1789990000.0,
          "ready": true,
          "approval": "approved",
          "approval_reason": null,
          "approval_at": 1790000100.0
        }
      },
      "DevicePage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Device"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "DeviceCreate": {
        "type": "object",
        "required": [
          "device_id",
          "profile",
          "site",
          "facility"
        ],
        "additionalProperties": false,
        "properties": {
          "device_id": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",
            "description": "Unique across every tenant's devices and gateways. An id starting with `agritrace-`, in any letter case, is reserved for the platform's own broker identities and refused (400).",
            "x-sdk-description": "Unique across every tenant's devices and gateways."
          },
          "profile": {
            "type": "string",
            "description": "The id of a device profile the server knows; any other id is refused. The profiles, each served as a file: `vn.agritrace.air-th-xy-md02` (/developers/downloads/profiles/air-th-xy-md02.json); `vn.agritrace.durian-knocker` (/developers/downloads/profiles/durian-knocker.json); `vn.agritrace.gateway` (/developers/downloads/profiles/gateway.json), a gateway's own status heartbeat, refused for a device (`invalid profile`); `vn.agritrace.harvest-app` (/developers/downloads/profiles/harvest-app.json); `vn.agritrace.irrigation-controller` (/developers/downloads/profiles/irrigation-controller.json); `vn.agritrace.pack-station` (/developers/downloads/profiles/pack-station.json); `vn.agritrace.rain-ub-ra-n1` (/developers/downloads/profiles/rain-ub-ra-n1.json); `vn.agritrace.reefer-logger` (/developers/downloads/profiles/reefer-logger.json); `vn.agritrace.scale-serial` (/developers/downloads/profiles/scale-serial.json); `vn.agritrace.soil-rs485-4in1-ec` (/developers/downloads/profiles/soil-rs485-4in1-ec.json); `vn.agritrace.soil-rs485-4in1` (/developers/downloads/profiles/soil-rs485-4in1.json).",
            "x-sdk-description": "The id of a device profile the server knows; any other id is refused. The profiles, each served as a file: `vn.agritrace.durian-knocker` (/developers/downloads/profiles/durian-knocker.json); `vn.agritrace.harvest-app` (/developers/downloads/profiles/harvest-app.json); `vn.agritrace.pack-station` (/developers/downloads/profiles/pack-station.json); `vn.agritrace.reefer-logger` (/developers/downloads/profiles/reefer-logger.json); `vn.agritrace.scale-serial` (/developers/downloads/profiles/scale-serial.json); `vn.agritrace.soil-rs485-4in1` (/developers/downloads/profiles/soil-rs485-4in1.json)."
          },
          "site": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"
          },
          "facility": {
            "type": "string",
            "description": "A facility code of the caller's tenant."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "vendor_model": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "serial": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          }
        }
      },
      "DeviceUpdate": {
        "type": "object",
        "minProperties": 1,
        "additionalProperties": false,
        "properties": {
          "status": {
            "enum": [
              "active",
              "inactive"
            ]
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "vendor_model": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "serial": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          }
        }
      },
      "CommandPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Command"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "Gateway": {
        "type": "object",
        "required": [
          "gateway_id",
          "tenant",
          "site",
          "facility",
          "display_name",
          "status",
          "approval",
          "approval_reason",
          "approval_at"
        ],
        "additionalProperties": false,
        "properties": {
          "gateway_id": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "site": {
            "type": "string"
          },
          "facility": {
            "type": [
              "string",
              "null"
            ]
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "type": "string"
          },
          "approval": {
            "type": "string",
            "enum": [
              "pending",
              "approved",
              "rejected"
            ],
            "description": "Platform approval (#201): `pending` until a platform admin approves or rejects it. Only evidence from an approved device, signed by its own key or an approved gateway's, counts as Device-recorded or above; evidence from a pending or rejected one is stored and counts as Self-declared."
          },
          "approval_reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "The reason of a rejection; null otherwise."
          },
          "approval_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the last approval decision."
          }
        },
        "example": {
          "gateway_id": "gw-01",
          "tenant": "coop-dl",
          "site": "ph1",
          "facility": "VN-TGPH-021",
          "display_name": "Packing hall gateway",
          "status": "active",
          "approval": "approved",
          "approval_reason": null,
          "approval_at": 1790000100.0
        }
      },
      "GatewayHeartbeatStatus": {
        "type": "object",
        "required": [
          "gateway_id",
          "heartbeat"
        ],
        "additionalProperties": false,
        "properties": {
          "gateway_id": {
            "type": "string"
          },
          "heartbeat": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/GatewayHeartbeat"
              },
              {
                "type": "null"
              }
            ],
            "description": "The newest heartbeat; null until the gateway sent one."
          }
        },
        "example": {
          "gateway_id": "gw-01",
          "heartbeat": {
            "received_at": 1790100030.25,
            "time": "2026-09-23T08:00:30.000+00:00",
            "seq": 2881,
            "signed": true,
            "outbox_depth": 3,
            "dead_letter_count": 0,
            "link": {
              "state": "connected"
            },
            "peripherals_ready": [
              {
                "device": "knk-1",
                "ready": true
              },
              {
                "device": "scale-1",
                "ready": false
              }
            ]
          }
        }
      },
      "GatewayStatusSeries": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "gateway_id",
          "grain",
          "bucket_s",
          "from",
          "to",
          "items"
        ],
        "description": "#128: a gateway's status series: samples (grain minute) or rollups (hourly, daily), oldest first.",
        "properties": {
          "gateway_id": {
            "type": "string"
          },
          "grain": {
            "type": "string",
            "enum": [
              "minute",
              "hourly",
              "daily"
            ]
          },
          "bucket_s": {
            "type": "number",
            "description": "Bucket width in seconds: 60, 3600 or 86400."
          },
          "from": {
            "type": "number",
            "description": "Start of the range read, Unix seconds: aligned down to the grain and clipped to what is kept."
          },
          "to": {
            "type": "number",
            "description": "End of the range (excluded), Unix seconds."
          },
          "items": {
            "type": "array",
            "items": {
              "oneOf": [
                {
                  "$ref": "#/components/schemas/GatewayStatusSample"
                },
                {
                  "$ref": "#/components/schemas/GatewayStatusBucket"
                }
              ]
            },
            "description": "Samples for grain minute, rollups otherwise."
          }
        },
        "example": {
          "gateway_id": "gw-01",
          "grain": "hourly",
          "bucket_s": 3600.0,
          "from": 1790100000.0,
          "to": 1790107200.0,
          "items": [
            {
              "bucket_start": 1790100000.0,
              "samples": 60,
              "outbox_depth": {
                "min": 0,
                "max": 12,
                "mean": 2.5,
                "count": 60
              },
              "dead_letter_count": {
                "min": 0,
                "max": 0,
                "mean": 0.0,
                "count": 60
              },
              "peripherals_ready": {
                "min": 1,
                "max": 2,
                "mean": 1.9,
                "count": 60
              },
              "peripherals_total": {
                "min": 2,
                "max": 2,
                "mean": 2.0,
                "count": 60
              },
              "link": {
                "connected": 58,
                "disconnected": 2,
                "unknown": 0
              }
            }
          ]
        }
      },
      "GatewayStatusSample": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "minute",
          "received_at",
          "time",
          "seq",
          "signed",
          "outbox_depth",
          "dead_letter_count",
          "link_state",
          "peripherals_ready",
          "peripherals_total"
        ],
        "description": "The heartbeat stored for one UTC minute. A value the heartbeat did not carry is null.",
        "properties": {
          "minute": {
            "type": "number",
            "description": "Start of the UTC minute of reception, Unix seconds."
          },
          "received_at": {
            "type": "number",
            "description": "When the server received it, Unix seconds."
          },
          "time": {
            "type": "string",
            "description": "The gateway's own time of the heartbeat."
          },
          "seq": {
            "type": "integer"
          },
          "signed": {
            "type": "boolean"
          },
          "outbox_depth": {
            "type": [
              "integer",
              "null"
            ]
          },
          "dead_letter_count": {
            "type": [
              "integer",
              "null"
            ]
          },
          "link_state": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "connected",
              "disconnected",
              "unknown",
              null
            ]
          },
          "peripherals_ready": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The devices listed as ready."
          },
          "peripherals_total": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The devices listed."
          }
        }
      },
      "GatewayStatusBucket": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "bucket_start",
          "samples",
          "outbox_depth",
          "dead_letter_count",
          "peripherals_ready",
          "peripherals_total",
          "link"
        ],
        "description": "An hourly rollup, or a day's hourly rollups merged.",
        "properties": {
          "bucket_start": {
            "type": "number",
            "description": "Start of the UTC hour or day, Unix seconds."
          },
          "samples": {
            "type": "integer"
          },
          "outbox_depth": {
            "$ref": "#/components/schemas/GatewayStatusStat"
          },
          "dead_letter_count": {
            "$ref": "#/components/schemas/GatewayStatusStat"
          },
          "peripherals_ready": {
            "$ref": "#/components/schemas/GatewayStatusStat",
            "description": "The devices the gateway listed as ready."
          },
          "peripherals_total": {
            "$ref": "#/components/schemas/GatewayStatusStat",
            "description": "The devices the gateway listed."
          },
          "link": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "connected",
              "disconnected",
              "unknown"
            ],
            "description": "The samples per uplink state (a sample without one is in none).",
            "properties": {
              "connected": {
                "type": "integer"
              },
              "disconnected": {
                "type": "integer"
              },
              "unknown": {
                "type": "integer"
              }
            }
          }
        }
      },
      "GatewayStatusStat": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "min",
          "max",
          "mean",
          "count"
        ],
        "description": "One value over a bucket's samples that carried it.",
        "properties": {
          "min": {
            "type": [
              "integer",
              "null"
            ]
          },
          "max": {
            "type": [
              "integer",
              "null"
            ]
          },
          "mean": {
            "type": [
              "number",
              "null"
            ],
            "description": "Null when no sample carried the value."
          },
          "count": {
            "type": "integer",
            "description": "The samples that carried the value."
          }
        }
      },
      "GatewayHeartbeat": {
        "type": "object",
        "required": [
          "received_at",
          "time",
          "seq",
          "signed",
          "outbox_depth",
          "dead_letter_count",
          "link",
          "peripherals_ready"
        ],
        "additionalProperties": false,
        "properties": {
          "received_at": {
            "type": "number",
            "description": "Unix seconds when the server received it."
          },
          "time": {
            "type": "string",
            "description": "The gateway's own time of the heartbeat (ISO 8601 with its UTC offset)."
          },
          "seq": {
            "type": "integer",
            "minimum": 0,
            "description": "The gateway's sequence number of the heartbeat."
          },
          "signed": {
            "type": "boolean",
            "description": "Signed with one of the gateway's own keys (false only where the server accepts unsigned envelopes)."
          },
          "outbox_depth": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "description": "`gateway.outbox_depth`: messages waiting in the gateway's store-and-forward queue."
          },
          "dead_letter_count": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "description": "`gateway.dead_letter_count`: messages the server refused for good that the gateway keeps."
          },
          "link": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/GatewayLink"
              },
              {
                "type": "null"
              }
            ],
            "description": "`gateway.link`: the gateway's uplink as it last observed it."
          },
          "peripherals_ready": {
            "type": [
              "array",
              "null"
            ],
            "maxItems": 256,
            "items": {
              "$ref": "#/components/schemas/GatewayPeripheral"
            },
            "description": "`gateway.peripherals_ready`: each device the gateway serves and whether its driver is ready."
          }
        }
      },
      "GatewayLink": {
        "type": "object",
        "required": [
          "state"
        ],
        "additionalProperties": false,
        "properties": {
          "state": {
            "type": "string",
            "enum": [
              "connected",
              "disconnected",
              "unknown"
            ]
          },
          "last_error": {
            "type": "string",
            "description": "The text of the gateway's last uplink error."
          }
        }
      },
      "GatewayPeripheral": {
        "type": "object",
        "required": [
          "device",
          "ready"
        ],
        "additionalProperties": false,
        "properties": {
          "device": {
            "type": "string"
          },
          "ready": {
            "type": "boolean"
          }
        }
      },
      "GatewayPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Gateway"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "GatewayCreate": {
        "type": "object",
        "required": [
          "gateway_id",
          "site"
        ],
        "additionalProperties": false,
        "properties": {
          "gateway_id": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",
            "description": "Unique across every tenant's gateways and devices. An id starting with `agritrace-`, in any letter case, is reserved for the platform's own broker identities and refused (400).",
            "x-sdk-description": "Unique across every tenant's gateways and devices."
          },
          "site": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"
          },
          "facility": {
            "type": [
              "string",
              "null"
            ],
            "description": "A facility code of the caller's tenant."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          }
        }
      },
      "Key": {
        "type": "object",
        "description": "A device or gateway public key. The PEM is never returned; `fingerprint_sha256` is the SHA-256 of the key's SubjectPublicKeyInfo DER and `fingerprint` its short display form.",
        "required": [
          "kid",
          "owner_type",
          "owner_id",
          "status",
          "created_at",
          "revoked_at",
          "revoke_reason",
          "revoked_by",
          "fingerprint_sha256",
          "fingerprint",
          "approval"
        ],
        "additionalProperties": false,
        "properties": {
          "kid": {
            "type": "string"
          },
          "owner_type": {
            "enum": [
              "device",
              "gateway"
            ]
          },
          "owner_id": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "description": "`active` or `revoked`; only active keys are accepted by ingest."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "rotation",
              "compromise",
              null
            ]
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "fingerprint_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "fingerprint": {
            "type": "string",
            "description": "First four and last four hex characters, e.g. `3f9a…c21e`."
          },
          "approval": {
            "type": "string",
            "enum": [
              "pending",
              "approved"
            ],
            "description": "#201: `pending` until a platform admin approves its device or gateway listing this key; only evidence signed with an approved key counts as Device-recorded or above (the console shows it as waiting for CropPath)."
          }
        },
        "example": {
          "kid": "knk-1-2026",
          "owner_type": "device",
          "owner_id": "knk-1",
          "status": "active",
          "created_at": 1790000000.5,
          "revoked_at": null,
          "revoke_reason": null,
          "revoked_by": null,
          "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
          "fingerprint": "19fc…e0d9",
          "approval": "approved"
        }
      },
      "KeyPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Key"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "KeyCreate": {
        "type": "object",
        "required": [
          "kid",
          "owner_type",
          "owner_id",
          "public_key_pem"
        ],
        "additionalProperties": false,
        "properties": {
          "kid": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",
            "description": "Unique across every tenant."
          },
          "owner_type": {
            "enum": [
              "device",
              "gateway"
            ]
          },
          "owner_id": {
            "type": "string",
            "description": "A device or gateway of the caller's tenant."
          },
          "public_key_pem": {
            "type": "string",
            "maxLength": 1024,
            "description": "One `PUBLIC KEY` PEM block holding an EC P-256 SubjectPublicKeyInfo."
          }
        }
      },
      "KeyRevoke": {
        "type": "object",
        "required": [
          "reason"
        ],
        "additionalProperties": false,
        "properties": {
          "reason": {
            "enum": [
              "rotation",
              "compromise"
            ]
          }
        }
      },
      "GeoJsonPolygon": {
        "type": "object",
        "required": [
          "type",
          "coordinates"
        ],
        "additionalProperties": false,
        "description": "A GeoJSON Polygon or MultiPolygon in WGS 84. Never public: only the owning tenant_admin and platform_admin see it.",
        "properties": {
          "type": {
            "enum": [
              "Polygon",
              "MultiPolygon"
            ]
          },
          "coordinates": {
            "type": "array",
            "minItems": 1,
            "description": "Polygon: closed rings of [longitude, latitude] (at least 4 positions each, first equals last); MultiPolygon: 1 to 64 such polygons. At most 5000 positions and 256 KiB in all."
          }
        },
        "example": {
          "type": "Polygon",
          "coordinates": [
            [
              [
                106.1,
                10.4
              ],
              [
                106.2,
                10.4
              ],
              [
                106.2,
                10.5
              ],
              [
                106.1,
                10.5
              ],
              [
                106.1,
                10.4
              ]
            ]
          ]
        }
      },
      "Grower": {
        "type": "object",
        "required": [
          "id",
          "tenant",
          "display_name",
          "cooperative",
          "public_consent",
          "consent_at",
          "consent_date",
          "consent_scope",
          "created_at",
          "updated_at"
        ],
        "additionalProperties": false,
        "description": "A grower (personal data) of one tenant, as the caller may see it.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "tenant": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "description": "Present only for the owning tenant_admin and platform_admin, or for other readers when public_consent is on."
          },
          "display_name": {
            "type": "string",
            "description": "The name with public consent, otherwise `Co-op member #<id>`."
          },
          "cooperative": {
            "type": [
              "string",
              "null"
            ]
          },
          "public_consent": {
            "type": "boolean",
            "description": "Explicit consent to show the grower's name publicly."
          },
          "consent_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds consent was given; null without consent."
          },
          "consent_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The day the grower gave the consent (YYYY-MM-DD, not after today); null without consent. Staff only, never on a public route."
          },
          "consent_scope": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "What the consent covers, as recorded from the consent form (staff-only text); null without consent or when not recorded. Never on a public route."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          }
        },
        "example": {
          "id": 12,
          "tenant": "coop-dl",
          "display_name": "Co-op member #12",
          "cooperative": "HTX Ngu Hiep",
          "public_consent": false,
          "consent_at": null,
          "consent_date": null,
          "consent_scope": null,
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5,
          "name": "Nguyen Van An"
        }
      },
      "GrowerPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Grower"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "GrowerCreate": {
        "type": "object",
        "required": [
          "name"
        ],
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "cooperative": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "public_consent": {
            "type": "boolean",
            "default": false
          },
          "consent_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The day the grower gave the consent (YYYY-MM-DD, not after today). Accepted only when public_consent is (or becomes) true; withdrawing the consent clears it."
          },
          "consent_scope": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "What the consent covers (staff-only text). Accepted only when public_consent is (or becomes) true; withdrawing the consent clears it."
          }
        }
      },
      "GrowerUpdate": {
        "type": "object",
        "required": [],
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "cooperative": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "public_consent": {
            "type": "boolean"
          },
          "consent_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The day the grower gave the consent (YYYY-MM-DD, not after today). Accepted only when public_consent is (or becomes) true; withdrawing the consent clears it."
          },
          "consent_scope": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "What the consent covers (staff-only text). Accepted only when public_consent is (or becomes) true; withdrawing the consent clears it."
          }
        },
        "minProperties": 1
      },
      "GrowingArea": {
        "type": "object",
        "required": [
          "code",
          "tenant",
          "name",
          "crop",
          "variety",
          "province",
          "district",
          "commune",
          "area_ha",
          "yield_kg_per_ha",
          "trees",
          "planted_year",
          "grower_id",
          "gacc_puc_code",
          "source",
          "approved_at",
          "created_at",
          "updated_at",
          "registry_changed_at",
          "cap_kg",
          "approval_current",
          "grower"
        ],
        "additionalProperties": false,
        "description": "A growing area. The cap is area_ha times yield_kg_per_ha.",
        "properties": {
          "code": {
            "type": "string"
          },
          "tenant": {
            "type": [
              "string",
              "null"
            ],
            "description": "Owning tenant; null for an area registered before migration 7 or by seed/provisioning (readable by every tenant, writable by platform_admin only)."
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "crop": {
            "type": [
              "string",
              "null"
            ]
          },
          "variety": {
            "type": [
              "string",
              "null"
            ]
          },
          "province": {
            "type": [
              "string",
              "null"
            ]
          },
          "district": {
            "type": [
              "string",
              "null"
            ]
          },
          "commune": {
            "type": [
              "string",
              "null"
            ]
          },
          "area_ha": {
            "type": "number"
          },
          "yield_kg_per_ha": {
            "type": "number"
          },
          "trees": {
            "type": [
              "integer",
              "null"
            ]
          },
          "planted_year": {
            "type": [
              "integer",
              "null"
            ]
          },
          "grower_id": {
            "type": [
              "integer",
              "null"
            ]
          },
          "gacc_puc_code": {
            "type": [
              "string",
              "null"
            ],
            "description": "GACC registration of the production unit."
          },
          "source": {
            "enum": [
              "seed",
              "manual"
            ]
          },
          "approved_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null until a platform admin approves."
          },
          "created_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null for a seeded (legacy) area."
          },
          "updated_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null for a seeded (legacy) area."
          },
          "registry_changed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the last change of the crop or variety (L8 #33); an approval older than it no longer covers the record."
          },
          "cap_kg": {
            "type": "number",
            "description": "The volume cap in kg: area_ha times yield_kg_per_ha, recomputed on every read (an edit of either input changes it, and its audit row records the cap before and after). Never public."
          },
          "approval_current": {
            "type": "boolean",
            "description": "Whether a platform approval covers the record as it is now: given, and newer than registry_changed_at (L8 #33). False until approved, and again after a crop or variety edit until re-approved. A seeded area (source seed) is never approved. Never public."
          },
          "grower": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/Grower"
              },
              {
                "type": "null"
              }
            ]
          },
          "polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ],
            "description": "Present only for the owning tenant_admin and platform_admin."
          },
          "province_code": {
            "description": "The province's official 2-digit code, in the list `admin_units_version`; null when not coded. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "The commune's official 5-digit code, in the list `admin_units_version`; null when not coded. A code is only meaningful with its version (codes were reused across the 2025 reform). Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "admin_units_version": {
            "description": "The version of the official list the codes were taken from (for example `vn-2026-10-17`); null without codes. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^vn-[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "address_before_reform": {
            "description": "The province, district and commune text the record held before it was coded, or the text a request gave through the deprecated text path; kept for good once set. Null for a record entered with codes. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "province",
              "district",
              "commune"
            ],
            "properties": {
              "province": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "district": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "commune": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "x-not-in-sdk": true
          },
          "address_status": {
            "description": "`coded`: the codes are set from the official list; `choose_commune`: the old commune was split, a person picks one of `address_candidates`; `needs_commune`: no codes yet (given as text, or before the reform), a person picks the commune; `outside_vietnam`: a company profile in another country, where the codes do not apply. Null for a record not reviewed since the codes were introduced. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "coded",
              "choose_commune",
              "needs_commune",
              "outside_vietnam",
              null
            ],
            "x-not-in-sdk": true
          },
          "address_candidates": {
            "description": "For `choose_commune`: the official commune codes to pick from; else null. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string",
              "pattern": "^[0-9]{5}$"
            },
            "x-not-in-sdk": true
          }
        },
        "example": {
          "code": "VN-TGOR-0387",
          "tenant": "coop-dl",
          "name": "Orchard 387",
          "crop": "durian",
          "variety": "Ri6",
          "province": "Tien Giang",
          "district": "Cai Lay",
          "commune": "Ngu Hiep",
          "area_ha": 2.0,
          "yield_kg_per_ha": 10000.0,
          "trees": 240,
          "planted_year": 2015,
          "grower_id": 12,
          "gacc_puc_code": "VNPUC-TG-0387",
          "source": "manual",
          "approved_at": null,
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5,
          "registry_changed_at": null,
          "cap_kg": 20000.0,
          "approval_current": false,
          "grower": {
            "id": 12,
            "tenant": "coop-dl",
            "display_name": "Co-op member #12",
            "cooperative": "HTX Ngu Hiep",
            "public_consent": false,
            "consent_at": null,
            "consent_date": null,
            "consent_scope": null,
            "created_at": 1790000000.5,
            "updated_at": 1790000000.5,
            "name": "Nguyen Van An"
          },
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.2,
                  10.4
                ],
                [
                  106.2,
                  10.5
                ],
                [
                  106.1,
                  10.5
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          }
        }
      },
      "GrowingAreaPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/GrowingArea"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "GrowingAreaCreate": {
        "type": "object",
        "required": [
          "code",
          "area_ha",
          "yield_kg_per_ha"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z]{2}(-[A-Z0-9]{1,12}){1,4}$",
            "maxLength": 64
          },
          "area_ha": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 100000
          },
          "yield_kg_per_ha": {
            "type": "number",
            "minimum": 0,
            "maximum": 1000000
          },
          "gacc_puc_code": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64
          },
          "name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "crop": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64
          },
          "variety": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: the province as free text. Send `province_code` and `commune_code` instead. A body that gives the address as text only is still accepted until the sunset: the record is stored as not yet coded (`address_status` `needs_commune`) and the answer carries the `Deprecation`, `Sunset` and `Link` headers.",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: Viet Nam has had no district level since 1 July 2025. Send `province_code` and `commune_code` instead; with them `district` must be absent or null (400 `district_with_codes`).",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "commune": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: the commune as free text. Send `province_code` and `commune_code` instead; the server then writes the official name here.",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "province_code": {
            "description": "#273: the province (tỉnh or thành phố trực thuộc trung ương) by its official 2-digit code in the administrative units list in force (`getAdminUnits`). Sent with `commune_code`, both or neither; with them `province`, `district` and `commune` must be absent or null and the server writes the official names.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "#273: the commune (xã, phường or đặc khu) by its official 5-digit code in the administrative units list in force (`getAdminUnits` with `province`). Sent with `province_code`, both or neither; the commune must lie in that province by the list, never by its digits.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ]
          },
          "trees": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "maximum": 10000000
          },
          "planted_year": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1900,
            "maximum": 2100
          },
          "grower_id": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "description": "A grower of the area's owning tenant."
          }
        }
      },
      "GrowingAreaUpdate": {
        "type": "object",
        "required": [],
        "additionalProperties": false,
        "description": "A tenant_admin of the owner may change name, crop, variety, the address (`province_code` and `commune_code`, or the deprecated province, district and commune text), polygon, trees, planted_year and grower_id; a platform_admin also area_ha, yield_kg_per_ha, gacc_puc_code and (once, on an unowned area) tenant.",
        "properties": {
          "name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "crop": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64
          },
          "variety": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: the province as free text. Send `province_code` and `commune_code` instead. A body that gives the address as text only is still accepted until the sunset: the record is stored as not yet coded (`address_status` `needs_commune`) and the answer carries the `Deprecation`, `Sunset` and `Link` headers.",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: Viet Nam has had no district level since 1 July 2025. Send `province_code` and `commune_code` instead; with them `district` must be absent or null (400 `district_with_codes`).",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "commune": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: the commune as free text. Send `province_code` and `commune_code` instead; the server then writes the official name here.",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "province_code": {
            "description": "#273: the province (tỉnh or thành phố trực thuộc trung ương) by its official 2-digit code in the administrative units list in force (`getAdminUnits`). Sent with `commune_code`, both or neither; with them `province`, `district` and `commune` must be absent or null and the server writes the official names.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "#273: the commune (xã, phường or đặc khu) by its official 5-digit code in the administrative units list in force (`getAdminUnits` with `province`). Sent with `province_code`, both or neither; the commune must lie in that province by the list, never by its digits.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ]
          },
          "trees": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "maximum": 10000000
          },
          "planted_year": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1900,
            "maximum": 2100
          },
          "grower_id": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "description": "A grower of the area's owning tenant."
          },
          "area_ha": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 100000
          },
          "yield_kg_per_ha": {
            "type": "number",
            "minimum": 0,
            "maximum": 1000000
          },
          "gacc_puc_code": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64
          },
          "tenant": {
            "type": "string",
            "description": "platform_admin only: claim an unowned area for a registered tenant (once)."
          }
        },
        "minProperties": 1,
        "x-sdk-description": "A tenant_admin of the owner may change name, crop, variety, province, district, commune, polygon, trees, planted_year and grower_id; a platform_admin also area_ha, yield_kg_per_ha, gacc_puc_code and (once, on an unowned area) tenant."
      },
      "GrowingAreaVolume": {
        "type": "object",
        "required": [
          "growing_area",
          "season",
          "declared_kg",
          "cap_kg",
          "headroom_kg"
        ],
        "additionalProperties": false,
        "properties": {
          "growing_area": {
            "type": "string"
          },
          "season": {
            "type": "string"
          },
          "declared_kg": {
            "type": "number"
          },
          "cap_kg": {
            "type": [
              "number",
              "null"
            ],
            "description": "area_ha times yield_kg_per_ha; null when the growing area is unknown or is a tenant-created area not yet approved by a platform admin."
          },
          "headroom_kg": {
            "type": [
              "number",
              "null"
            ],
            "description": "cap_kg minus declared_kg (negative when over the cap); null when cap_kg is null."
          }
        },
        "description": "Volume.cap_kg, declared_kg (summed across all tenants) and the headroom left.",
        "example": {
          "growing_area": "VN-TGOR-0387",
          "season": "2026",
          "declared_kg": 2000.0,
          "cap_kg": 20000.0,
          "headroom_kg": 18000.0
        }
      },
      "SprayRecord": {
        "type": "object",
        "required": [
          "id",
          "growing_area",
          "sprayed_on",
          "product",
          "active_ingredient",
          "withholding_days",
          "evidence_sha256",
          "created_at",
          "safe_from",
          "evaluated_on",
          "withholding_status"
        ],
        "additionalProperties": false,
        "description": "A spray record with its withholding status.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "growing_area": {
            "type": "string"
          },
          "sprayed_on": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "product": {
            "type": "string"
          },
          "active_ingredient": {
            "type": [
              "string",
              "null"
            ]
          },
          "withholding_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 365
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "safe_from": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "sprayed_on plus withholding_days: the first day a harvest is allowed."
          },
          "evaluated_on": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The harvest date the status was judged against (today's UTC date when none was given)."
          },
          "withholding_status": {
            "enum": [
              "ok",
              "violated"
            ],
            "description": "violated when sprayed_on <= evaluated_on < safe_from."
          }
        },
        "example": {
          "id": 3,
          "growing_area": "VN-TGOR-0387",
          "sprayed_on": "2026-09-01",
          "product": "Ridomil Gold",
          "active_ingredient": "metalaxyl-M",
          "withholding_days": 14,
          "evidence_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c",
          "created_at": 1790000000.5,
          "safe_from": "2026-09-15",
          "evaluated_on": "2026-09-14",
          "withholding_status": "violated"
        }
      },
      "SprayRecordPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SprayRecord"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "SprayRecordCreate": {
        "type": "object",
        "required": [
          "sprayed_on",
          "product",
          "withholding_days"
        ],
        "additionalProperties": false,
        "properties": {
          "sprayed_on": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "product": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "active_ingredient": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "withholding_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 365
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$"
          }
        }
      },
      "Certification": {
        "type": "object",
        "required": [
          "id",
          "growing_area",
          "scheme",
          "number",
          "issuer",
          "valid_from",
          "valid_to",
          "evidence_sha256",
          "created_at",
          "status"
        ],
        "additionalProperties": false,
        "description": "A certification of a growing area (e.g. VietGAP). It is verified when its scheme is one of the fixed list (see CertificationCreate), it has an `issuer` and an `evidence_sha256`, and a GLOBALG.A.P. `number` is a GGN; otherwise (e.g. a record written before #156, or sent without them) it is unverified and never counts towards a lot's trust tier.",
        "x-sdk-description": "A certification of a growing area (e.g. VietGAP).",
        "properties": {
          "id": {
            "type": "integer"
          },
          "growing_area": {
            "type": "string"
          },
          "scheme": {
            "type": "string"
          },
          "number": {
            "type": "string"
          },
          "issuer": {
            "type": [
              "string",
              "null"
            ]
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "status": {
            "enum": [
              "valid",
              "expired",
              "not_yet_valid"
            ],
            "description": "Against today's UTC date."
          },
          "verified": {
            "type": "boolean",
            "description": "#269 review, with listCertifications `verified=1` only: whether the server counts this certification as verified (the rule of this object's description; also false for an ISO 22000, FSSC 22000, BRCGS or IFS certification recorded on the growing area since these schemes moved to the facility). Only a verified one counts towards a lot's trust tier.",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "id": 1,
          "growing_area": "VN-TGOR-0387",
          "scheme": "VietGAP",
          "number": "VG-TG-0387",
          "issuer": "NAFIQAD",
          "valid_from": "2025-01-01",
          "valid_to": "2027-12-31",
          "evidence_sha256": null,
          "created_at": 1790000000.5,
          "status": "valid"
        }
      },
      "CertificationPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Certification"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "CertificationCreate": {
        "type": "object",
        "required": [
          "scheme",
          "number",
          "valid_from",
          "valid_to"
        ],
        "additionalProperties": false,
        "properties": {
          "scheme": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "The certification scheme. A verified certification names one of VietGAP, GLOBALG.A.P., Organic JAS, Organic EU, Organic USDA, ISO 22000, FSSC 22000, BRCGS, IFS and HACCP (compared exactly), as the console sends it; any other text is accepted and stored, and the certification is unverified. ISO 22000, FSSC 22000, BRCGS and IFS certify a packing house (#269): record new ones on the facility (createFacilityCertification). A growing-area certification of these schemes is still accepted and stored as sent, but one recorded from this change on is unverified whatever it holds (it never counts towards a lot's trust tier); one recorded before is judged as before."
          },
          "number": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "The certificate number. For a verified GLOBALG.A.P. certification, the producer's GLOBALG.A.P. Number (GGN): its 13 digits without the \"GGN\" prefix, the last being the GS1 mod-10 check digit of the others."
          },
          "issuer": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "The certifier (certification body) that issued the certificate. Optional; without it the certification is unverified."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "Not before valid_from."
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "The SHA-256 of the certificate document, e.g. the PDF uploaded with PUT /v1/attachments/{sha256}. Optional; without it the certification is unverified."
          }
        },
        "description": "#156: a certification is verified when it names its scheme from the fixed list, its certifier (`issuer`) and the SHA-256 of the certificate document (`evidence_sha256`), and, for GLOBALG.A.P., a `number` that is the producer's GGN; the console always sends that shape. A request without them (as released clients send it: any scheme text, no certifier, no hash) is accepted and stored as sent, unverified: an unverified certification never counts towards a lot's trust tier (the harvest step's certification check counts verified certifications only).",
        "x-sdk-object": {
          "type": "object",
          "required": [
            "scheme",
            "number",
            "valid_from",
            "valid_to"
          ],
          "additionalProperties": false,
          "properties": {
            "scheme": {
              "type": "string",
              "minLength": 1,
              "maxLength": 64
            },
            "number": {
              "type": "string",
              "minLength": 1,
              "maxLength": 64
            },
            "issuer": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 200
            },
            "valid_from": {
              "type": "string",
              "format": "date",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
            },
            "valid_to": {
              "type": "string",
              "format": "date",
              "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
              "description": "Not before valid_from."
            },
            "evidence_sha256": {
              "type": [
                "string",
                "null"
              ],
              "pattern": "^[0-9a-f]{64}$"
            }
          }
        }
      },
      "SatelliteCheck": {
        "type": "object",
        "required": [
          "id",
          "growing_area",
          "image_date",
          "provider",
          "result",
          "cultivated_ha",
          "deforestation",
          "confidence",
          "image_sha256",
          "source",
          "created_at"
        ],
        "additionalProperties": false,
        "description": "A satellite check of a growing area.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "growing_area": {
            "type": "string"
          },
          "image_date": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "provider": {
            "type": "string"
          },
          "result": {
            "enum": [
              "match",
              "mismatch",
              "inconclusive"
            ],
            "description": "Whether the image matches the registered area."
          },
          "cultivated_ha": {
            "type": [
              "number",
              "null"
            ]
          },
          "deforestation": {
            "type": "boolean"
          },
          "confidence": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 1
          },
          "image_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the image attachment; the blob itself is stored elsewhere."
          },
          "source": {
            "enum": [
              "manual",
              "automatic"
            ],
            "description": "manual for every check recorded through this API."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          }
        },
        "example": {
          "id": 1,
          "growing_area": "VN-TGOR-0387",
          "image_date": "2026-09-20",
          "provider": "sentinel-2",
          "result": "match",
          "cultivated_ha": 1.9,
          "deforestation": false,
          "confidence": 0.86,
          "image_sha256": "9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c9f2c",
          "source": "manual",
          "created_at": 1790000000.5
        }
      },
      "SatelliteCheckPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SatelliteCheck"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "SatelliteCheckCreate": {
        "type": "object",
        "required": [
          "image_date",
          "provider",
          "result",
          "deforestation"
        ],
        "additionalProperties": false,
        "properties": {
          "image_date": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "provider": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "result": {
            "enum": [
              "match",
              "mismatch",
              "inconclusive"
            ]
          },
          "cultivated_ha": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 100000
          },
          "deforestation": {
            "type": "boolean"
          },
          "confidence": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 1
          },
          "image_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$"
          }
        }
      },
      "AttachmentStored": {
        "type": "object",
        "required": [
          "sha256",
          "media_type",
          "size"
        ],
        "additionalProperties": false,
        "description": "An uploaded blob as stored for its owner.",
        "properties": {
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "media_type": {
            "type": "string",
            "enum": [
              "application/pdf",
              "audio/wav",
              "image/jpeg",
              "image/png"
            ]
          },
          "size": {
            "type": "integer",
            "minimum": 0,
            "maximum": 1048576
          }
        },
        "example": {
          "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
          "media_type": "audio/wav",
          "size": 115244
        }
      },
      "AttachmentPeaks": {
        "type": "object",
        "required": [
          "sha256",
          "n",
          "channels",
          "sample_rate",
          "frames",
          "duration_s",
          "peaks"
        ],
        "additionalProperties": false,
        "description": "Waveform peaks: `n` buckets of [min, max] (normalised to -1..1) over all channels.",
        "properties": {
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "n": {
            "type": "integer",
            "minimum": 0,
            "maximum": 4096,
            "description": "Buckets returned."
          },
          "channels": {
            "type": "integer",
            "minimum": 1
          },
          "sample_rate": {
            "type": "integer",
            "minimum": 1
          },
          "frames": {
            "type": "integer",
            "minimum": 0
          },
          "duration_s": {
            "type": "number",
            "minimum": 0
          },
          "peaks": {
            "type": "array",
            "maxItems": 4096,
            "items": {
              "type": "array",
              "minItems": 2,
              "maxItems": 2,
              "items": {
                "type": "number",
                "minimum": -1,
                "maximum": 1
              }
            }
          }
        },
        "example": {
          "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
          "n": 4,
          "channels": 1,
          "sample_rate": 48000,
          "frames": 57600,
          "duration_s": 1.2,
          "peaks": [
            [
              -0.5,
              0.5
            ],
            [
              -0.25,
              0.75
            ],
            [
              0.0,
              0.0
            ],
            [
              -1.0,
              0.9999
            ]
          ]
        }
      },
      "Lot": {
        "type": "object",
        "required": [
          "tenant",
          "code",
          "seq",
          "public_id",
          "facility",
          "product",
          "variety",
          "growing_area",
          "harvest_date",
          "harvest_event_id",
          "destination",
          "gtin",
          "status",
          "created_at",
          "updated_at",
          "closed_at"
        ],
        "additionalProperties": false,
        "description": "A lot of one tenant (issue #26). `code` is unique within the tenant and links the lot to envelopes whose signed context names it; `seq` is the tenant's lot number (fruit codes); `public_id` is 128 random bits as hex, never derived from the code or seq. Status in wave 5: draft (created), open (a session was opened), closed (service-level close; the route comes with the seal).",
        "properties": {
          "tenant": {
            "type": "string"
          },
          "code": {
            "type": "string"
          },
          "seq": {
            "type": "integer",
            "minimum": 1
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$"
          },
          "facility": {
            "type": "string"
          },
          "product": {
            "type": "string"
          },
          "variety": {
            "type": [
              "string",
              "null"
            ]
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ]
          },
          "harvest_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date"
          },
          "harvest_event_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Id of the tenant's harvest envelope."
          },
          "destination": {
            "type": [
              "string",
              "null"
            ]
          },
          "gtin": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{14}$"
          },
          "status": {
            "enum": [
              "draft",
              "open",
              "paused",
              "closed",
              "packed",
              "shipped",
              "recalled",
              "withdrawn"
            ]
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "closed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null until closed."
          }
        },
        "example": {
          "tenant": "coop-dl",
          "code": "LO-260928-014",
          "seq": 14,
          "public_id": "5f0c8e2a9b7d4c1e8a3f6b2d9c0e7a14",
          "facility": "VN-TGPH-021",
          "product": "durian",
          "variety": "Ri6",
          "growing_area": "VN-TGOR-0387",
          "harvest_date": "2026-09-27",
          "harvest_event_id": null,
          "destination": "Huu Nghi border gate, Lang Son",
          "gtin": "00012345678905",
          "status": "open",
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5,
          "closed_at": null
        }
      },
      "LotPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Lot"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "LotCreate": {
        "type": "object",
        "required": [
          "code",
          "facility"
        ],
        "additionalProperties": false,
        "description": "The owner is the tenant the caller acts for; seq, public_id and status are set by the server.",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$"
          },
          "facility": {
            "type": "string",
            "description": "A facility of the caller's tenant (within an operator's facilities)."
          },
          "product": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "variety": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 64
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64,
            "description": "A growing-area code the tenant may read (its own or an unowned one)."
          },
          "harvest_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "YYYY-MM-DD, at most one day after today (UTC)."
          },
          "harvest_event_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64,
            "description": "Id of a stored harvest envelope of the tenant."
          },
          "destination": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200
          },
          "gtin": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{14}$",
            "description": "GTIN-14 with a valid GS1 check digit."
          }
        },
        "example": {
          "code": "LO-260928-014",
          "facility": "VN-TGPH-021",
          "variety": "Ri6",
          "growing_area": "VN-TGOR-0387",
          "harvest_date": "2026-09-27",
          "destination": "Huu Nghi border gate, Lang Son"
        }
      },
      "LotUpdate": {
        "type": "object",
        "minProperties": 1,
        "additionalProperties": false,
        "description": "Descriptive fields only; code, facility, seq, public_id, tenant and status are immutable here.",
        "properties": {
          "product": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "variety": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 64
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64,
            "description": "A growing-area code the tenant may read (its own or an unowned one)."
          },
          "harvest_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "YYYY-MM-DD, at most one day after today (UTC)."
          },
          "harvest_event_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64,
            "description": "Id of a stored harvest envelope of the tenant."
          },
          "destination": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200
          },
          "gtin": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{14}$",
            "description": "GTIN-14 with a valid GS1 check digit."
          }
        },
        "example": {
          "variety": "Ri6",
          "destination": null
        }
      },
      "LotCodeSuggestion": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code"
        ],
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$",
            "description": "A code `createLot` accepts, not used by the company when it was suggested: `LO-YYMMDD-NNN`."
          }
        }
      },
      "MeasurementSession": {
        "type": "object",
        "required": [
          "id",
          "tenant",
          "lot",
          "facility",
          "line",
          "status",
          "opened_by",
          "opened_at",
          "paused_at",
          "closed_at",
          "updated_at",
          "devices"
        ],
        "additionalProperties": false,
        "description": "A measurement session of one lot on one line (not a login session). At most one open or paused session holds a line, and a device is in at most one open or paused session.",
        "properties": {
          "id": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "facility": {
            "type": "string",
            "description": "The lot's facility."
          },
          "line": {
            "type": "string"
          },
          "status": {
            "enum": [
              "open",
              "paused",
              "closed"
            ]
          },
          "opened_by": {
            "type": "string",
            "description": "The principal that opened the session."
          },
          "opened_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "paused_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the last pause."
          },
          "closed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "devices": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Devices chosen when the session opened."
          }
        },
        "example": {
          "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
          "tenant": "coop-dl",
          "lot": "LO-260928-014",
          "facility": "VN-TGPH-021",
          "line": "A2",
          "status": "open",
          "opened_by": "operator@coop.example",
          "opened_at": 1790000000.5,
          "paused_at": null,
          "closed_at": null,
          "updated_at": 1790000000.5,
          "devices": [
            "knk-1",
            "scale-1"
          ]
        }
      },
      "MeasurementSessionList": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "description": "Every measurement session of one lot, newest first.",
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/MeasurementSession"
            }
          }
        }
      },
      "SessionCommand": {
        "type": "object",
        "required": [
          "device_id",
          "command_id",
          "status",
          "reason"
        ],
        "additionalProperties": false,
        "description": "The set_session outcome for one chosen device: pending (recorded, no transport configured), sent, failed (the transport refused it; the device's command list shows the failed row), refused (refused before any command was recorded: device_not_found when the device is missing, of another tenant or outside the caller's facilities, device_not_approved (#242) when the platform has not approved the device or no active approved key reaches it, its own or an approved gateway's at its site, invalid_command when its profile or the params do not allow it) or skipped (its profile does not declare set_session).",
        "x-sdk-description": "The set_session outcome for one chosen device: pending (recorded, no transport configured), sent, failed (the transport refused it; the device's command list shows the failed row), refused (refused before any command was recorded: device_not_found when the device is missing, of another tenant or outside the caller's facilities, invalid_command when its profile or the params do not allow it) or skipped (its profile does not declare set_session).",
        "properties": {
          "device_id": {
            "type": "string"
          },
          "command_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "enum": [
              "pending",
              "sent",
              "failed",
              "refused",
              "skipped"
            ]
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "not_declared",
              "dispatch_failed",
              "device_not_found",
              "device_not_approved",
              "invalid_command",
              null
            ],
            "x-sdk-enum": [
              "not_declared",
              "dispatch_failed",
              "device_not_found",
              "invalid_command",
              null
            ]
          }
        }
      },
      "MeasurementSessionOpened": {
        "type": "object",
        "required": [
          "id",
          "tenant",
          "lot",
          "facility",
          "line",
          "status",
          "opened_by",
          "opened_at",
          "paused_at",
          "closed_at",
          "updated_at",
          "devices",
          "commands"
        ],
        "additionalProperties": false,
        "description": "The new measurement session and the set_session outcome per chosen device.",
        "properties": {
          "id": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "facility": {
            "type": "string",
            "description": "The lot's facility."
          },
          "line": {
            "type": "string"
          },
          "status": {
            "enum": [
              "open",
              "paused",
              "closed"
            ]
          },
          "opened_by": {
            "type": "string",
            "description": "The principal that opened the session."
          },
          "opened_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "paused_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the last pause."
          },
          "closed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "devices": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Devices chosen when the session opened."
          },
          "commands": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SessionCommand"
            }
          }
        },
        "example": {
          "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
          "tenant": "coop-dl",
          "lot": "LO-260928-014",
          "facility": "VN-TGPH-021",
          "line": "A2",
          "status": "open",
          "opened_by": "operator@coop.example",
          "opened_at": 1790000000.5,
          "paused_at": null,
          "closed_at": null,
          "updated_at": 1790000000.5,
          "devices": [
            "knk-1",
            "scale-1"
          ],
          "commands": [
            {
              "device_id": "knk-1",
              "command_id": "9d2e7f40-1c3b-4a5e-8f6d-0b7c2a9e4d18",
              "status": "sent",
              "reason": null
            },
            {
              "device_id": "scale-1",
              "command_id": null,
              "status": "skipped",
              "reason": "not_declared"
            }
          ]
        }
      },
      "MeasurementSessionOpen": {
        "type": "object",
        "required": [
          "line"
        ],
        "additionalProperties": false,
        "properties": {
          "line": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{0,15}$"
          },
          "devices": {
            "type": "array",
            "maxItems": 16,
            "uniqueItems": true,
            "items": {
              "type": "string"
            },
            "description": "Active devices of the lot's facility. Default: every one whose profile declares set_session."
          }
        },
        "example": {
          "line": "A2",
          "devices": [
            "knk-1",
            "scale-1"
          ]
        }
      },
      "Fruit": {
        "type": "object",
        "required": [
          "tenant",
          "code",
          "n",
          "public_id",
          "lot",
          "session",
          "line",
          "operator",
          "status",
          "labels_printed_at",
          "created_at",
          "updated_at",
          "qr_url",
          "level",
          "level_pred",
          "maturity_class",
          "confidence",
          "model",
          "measured_at",
          "weight_kg",
          "level_sensory",
          "override",
          "pending_review",
          "grade",
          "eating_window",
          "record_tier",
          "knock_envelope_id",
          "scale_envelope_id",
          "override_envelope_id"
        ],
        "additionalProperties": false,
        "description": "A fruit record: identity, label fields and the measurements bound to it (L3).",
        "properties": {
          "tenant": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "pattern": "^Q-[0-9]{3,}-[0-9]{4,}$",
            "description": "Fruit code `Q-<lot seq>-<n>`, unique within the tenant."
          },
          "n": {
            "type": "integer",
            "minimum": 1,
            "description": "Position of the fruit in its lot: 1, 2, ... without gaps."
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "128 random bits (hex); the public handle of the fruit, never derived from code or n."
          },
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "session": {
            "type": "string",
            "description": "Measurement session id."
          },
          "line": {
            "type": "string",
            "description": "The session's line."
          },
          "operator": {
            "type": [
              "string",
              "null"
            ],
            "description": "Opaque operator id `user-<id>` of the signed-in user who allocated it; null for API tokens."
          },
          "status": {
            "enum": [
              "awaiting_device",
              "recorded",
              "overridden",
              "rejected",
              "remeasured"
            ],
            "description": "Fruit record state; allocation starts at awaiting_device."
          },
          "labels_printed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds the label was printed (allocation)."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "qr_url": {
            "type": "string",
            "format": "uri",
            "description": "The QR content: a GS1 Digital Link `<base>/01/<gtin>/10/<lot>/21/<serial>` (20-character random serial) when the lot has a GTIN and a lot code of at most 20 characters, else `<base>/q/<public_id>`. The base is the deployment's resolver origin, AGRITRACE_RESOLVER_BASE (default https://txng.theio.vn).",
            "x-sdk-description": "The QR content: a GS1 Digital Link `<base>/01/<gtin>/10/<lot>/21/<serial>` (20-character random serial) when the lot has a GTIN and a lot code of at most 20 characters, else `<base>/q/<public_id>`. The base is https://txng.theio.vn until the permanent resolver domain is chosen."
          },
          "level": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "Effective ripeness level (1 Non, 2 Gia, 3 Chin toi, 4 Chin ruc): level_sensory while an override is bound, else level_pred."
          },
          "level_pred": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "The level the knocker sent (`produce.ripeness_level`); null when it sent none (a `mature` class is level 2 or 3 and is never guessed)."
          },
          "maturity_class": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "immature",
              "mature",
              "overripe",
              "defect",
              "unknown",
              null
            ],
            "description": "The knocker's `produce.maturity_class`."
          },
          "confidence": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 1,
            "description": "Model confidence 0-1."
          },
          "model": {
            "type": [
              "string",
              "null"
            ],
            "description": "Model version that made the prediction."
          },
          "measured_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the knock (device event time)."
          },
          "weight_kg": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "description": "Net mass from the bound scale reading."
          },
          "level_sensory": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "The operator's sensory override (keys 1-4), if bound."
          },
          "override": {
            "type": "boolean",
            "description": "A sensory override is bound."
          },
          "pending_review": {
            "type": "boolean",
            "description": "Overlay: a bound envelope is quarantined and waits for review."
          },
          "grade": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "A",
              "B",
              "reject",
              null
            ],
            "description": "Grade under the tenant's rules for the lot's variety (else the platform default), derived when the fruit was last bound or reviewed; null until a signed knock, a level and a weight are known (a defect or a reject level grades reject at once)."
          },
          "eating_window": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/EatingWindow"
              },
              {
                "type": "null"
              }
            ]
          },
          "record_tier": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "self_declared",
              "device_recorded",
              "cross_checked",
              "lab_verified",
              null
            ],
            "description": "Trust tier of the fruit's own record, derived at read time; null until a knock is bound. Cross-checked needs the per-fruit volume quota, not reconciled yet."
          },
          "knock_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound knock envelope."
          },
          "scale_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound scale envelope."
          },
          "override_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound sensory-override envelope."
          }
        },
        "example": {
          "tenant": "coop-dl",
          "code": "Q-014-0129",
          "n": 129,
          "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
          "lot": "LO-260928-014",
          "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
          "line": "A2",
          "operator": "user-7",
          "status": "recorded",
          "labels_printed_at": 1790000000.5,
          "created_at": 1790000000.5,
          "updated_at": 1790560561.2,
          "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
          "level": 3,
          "level_pred": 3,
          "maturity_class": "mature",
          "confidence": 0.91,
          "model": "sf100-m3",
          "measured_at": 1790560560.0,
          "weight_kg": 2.84,
          "level_sensory": null,
          "override": false,
          "pending_review": false,
          "grade": "A",
          "eating_window": {
            "start_days": 3,
            "end_days": 4,
            "from_date": "2026-10-01",
            "to_date": "2026-10-02",
            "band": "ambient",
            "warning": null
          },
          "record_tier": "device_recorded",
          "knock_envelope_id": "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30",
          "scale_envelope_id": "6e3a1d9c-2b7f-4e8a-b5c4-9d0f1e2a3b47",
          "override_envelope_id": null
        }
      },
      "FruitPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Fruit"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "FruitLabel": {
        "type": "object",
        "required": [
          "code",
          "lot",
          "n",
          "line",
          "operator",
          "printed_at",
          "qr_url"
        ],
        "additionalProperties": false,
        "description": "What the label printer prints for the fruit.",
        "properties": {
          "code": {
            "type": "string"
          },
          "lot": {
            "type": "string"
          },
          "n": {
            "type": "integer",
            "minimum": 1
          },
          "line": {
            "type": "string"
          },
          "operator": {
            "type": [
              "string",
              "null"
            ]
          },
          "printed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "qr_url": {
            "type": "string",
            "format": "uri"
          },
          "label_code": {
            "type": "string",
            "pattern": "^[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}$",
            "description": "#326, in the fruit batch's answer with `label_code=1` only: the fruit's lookup code (#288) in its grouped form (three groups of five Crockford base 32 characters), derived from the fruit's public id. A label prints it beside the QR code, as the console's 40 x 30 mm label does; a person types it on the scan page when the QR code cannot be scanned, and `GET /v1/public/resolve` answers it with the fruit.",
            "example": "7YD1R-1YMWA-W5MVB",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "code": "Q-014-0129",
          "lot": "LO-260928-014",
          "n": 129,
          "line": "A2",
          "operator": "user-7",
          "printed_at": 1790000000.5,
          "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
        }
      },
      "FruitAllocated": {
        "type": "object",
        "required": [
          "tenant",
          "code",
          "n",
          "public_id",
          "lot",
          "session",
          "line",
          "operator",
          "status",
          "labels_printed_at",
          "created_at",
          "updated_at",
          "qr_url",
          "label",
          "commands",
          "level",
          "level_pred",
          "maturity_class",
          "confidence",
          "model",
          "measured_at",
          "weight_kg",
          "level_sensory",
          "override",
          "pending_review",
          "grade",
          "eating_window",
          "record_tier",
          "knock_envelope_id",
          "scale_envelope_id",
          "override_envelope_id"
        ],
        "additionalProperties": false,
        "description": "The new fruit, its label payload and the set_session outcome per device of the session.",
        "properties": {
          "tenant": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "pattern": "^Q-[0-9]{3,}-[0-9]{4,}$",
            "description": "Fruit code `Q-<lot seq>-<n>`, unique within the tenant."
          },
          "n": {
            "type": "integer",
            "minimum": 1,
            "description": "Position of the fruit in its lot: 1, 2, ... without gaps."
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "128 random bits (hex); the public handle of the fruit, never derived from code or n."
          },
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "session": {
            "type": "string",
            "description": "Measurement session id."
          },
          "line": {
            "type": "string",
            "description": "The session's line."
          },
          "operator": {
            "type": [
              "string",
              "null"
            ],
            "description": "Opaque operator id `user-<id>` of the signed-in user who allocated it; null for API tokens."
          },
          "status": {
            "enum": [
              "awaiting_device",
              "recorded",
              "overridden",
              "rejected",
              "remeasured"
            ],
            "description": "Fruit record state; allocation starts at awaiting_device."
          },
          "labels_printed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds the label was printed (allocation)."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "qr_url": {
            "type": "string",
            "format": "uri",
            "description": "The QR content: a GS1 Digital Link `<base>/01/<gtin>/10/<lot>/21/<serial>` (20-character random serial) when the lot has a GTIN and a lot code of at most 20 characters, else `<base>/q/<public_id>`. The base is the deployment's resolver origin, AGRITRACE_RESOLVER_BASE (default https://txng.theio.vn).",
            "x-sdk-description": "The QR content: a GS1 Digital Link `<base>/01/<gtin>/10/<lot>/21/<serial>` (20-character random serial) when the lot has a GTIN and a lot code of at most 20 characters, else `<base>/q/<public_id>`. The base is https://txng.theio.vn until the permanent resolver domain is chosen."
          },
          "label": {
            "$ref": "#/components/schemas/FruitLabel"
          },
          "commands": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SessionCommand"
            },
            "description": "The set_session outcome per device of the session."
          },
          "level": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "Effective ripeness level (1 Non, 2 Gia, 3 Chin toi, 4 Chin ruc): level_sensory while an override is bound, else level_pred."
          },
          "level_pred": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "The level the knocker sent (`produce.ripeness_level`); null when it sent none (a `mature` class is level 2 or 3 and is never guessed)."
          },
          "maturity_class": {
            "enum": [
              "immature",
              "mature",
              "overripe",
              "defect",
              "unknown",
              null
            ],
            "description": "The knocker's `produce.maturity_class`."
          },
          "confidence": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 1,
            "description": "Model confidence 0-1."
          },
          "model": {
            "type": [
              "string",
              "null"
            ],
            "description": "Model version that made the prediction."
          },
          "measured_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the knock (device event time)."
          },
          "weight_kg": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "description": "Net mass from the bound scale reading."
          },
          "level_sensory": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "The operator's sensory override (keys 1-4), if bound."
          },
          "override": {
            "type": "boolean",
            "description": "A sensory override is bound."
          },
          "pending_review": {
            "type": "boolean",
            "description": "Overlay: a bound envelope is quarantined and waits for review."
          },
          "grade": {
            "enum": [
              "A",
              "B",
              "reject",
              null
            ],
            "description": "Grade under the tenant's rules for the lot's variety (else the platform default), derived when the fruit was last bound or reviewed; null until a signed knock, a level and a weight are known (a defect or a reject level grades reject at once)."
          },
          "eating_window": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/EatingWindow"
              },
              {
                "type": "null"
              }
            ]
          },
          "record_tier": {
            "enum": [
              "self_declared",
              "device_recorded",
              "cross_checked",
              "lab_verified",
              null
            ],
            "description": "Trust tier of the fruit's own record, derived at read time; null until a knock is bound. Cross-checked needs the per-fruit volume quota, not reconciled yet."
          },
          "knock_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound knock envelope."
          },
          "scale_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound scale envelope."
          },
          "override_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound sensory-override envelope."
          }
        },
        "example": {
          "tenant": "coop-dl",
          "code": "Q-014-0129",
          "n": 129,
          "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
          "lot": "LO-260928-014",
          "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
          "line": "A2",
          "operator": "user-7",
          "status": "awaiting_device",
          "labels_printed_at": 1790000000.5,
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5,
          "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
          "label": {
            "code": "Q-014-0129",
            "lot": "LO-260928-014",
            "n": 129,
            "line": "A2",
            "operator": "user-7",
            "printed_at": 1790000000.5,
            "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
          },
          "commands": [
            {
              "device_id": "knk-1",
              "command_id": "9d2e7f40-1c3b-4a5e-8f6d-0b7c2a9e4d18",
              "status": "sent",
              "reason": null
            },
            {
              "device_id": "scale-1",
              "command_id": "1a6b3c8d-2e4f-4a7b-9c0d-5e8f1a2b3c4d",
              "status": "sent",
              "reason": null
            }
          ],
          "level": null,
          "level_pred": null,
          "maturity_class": null,
          "confidence": null,
          "model": null,
          "measured_at": null,
          "weight_kg": null,
          "level_sensory": null,
          "override": false,
          "pending_review": false,
          "grade": null,
          "eating_window": null,
          "record_tier": null,
          "knock_envelope_id": null,
          "scale_envelope_id": null,
          "override_envelope_id": null
        }
      },
      "FruitAllocate": {
        "type": "object",
        "maxProperties": 0,
        "additionalProperties": false,
        "description": "No fields: the operator is the caller, the line and lot are the session's.",
        "example": {}
      },
      "FruitActionRequest": {
        "type": "object",
        "required": [
          "type",
          "idempotency_key",
          "client_ts"
        ],
        "additionalProperties": false,
        "description": "An operator action on a fruit (L4).",
        "properties": {
          "type": {
            "enum": [
              "accept",
              "remeasure",
              "reject",
              "override"
            ]
          },
          "level": {
            "type": "integer",
            "minimum": 1,
            "maximum": 4,
            "description": "The sensory ripeness level (keys 1-4); required for override, refused otherwise."
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200,
            "pattern": "^(?![\\s\\S]*[\\x00-\\x1f\\x7f-\\x9f])[\\s\\S]*\\S",
            "description": "Optional free text without control characters (U+0000-U+001F, U+007F-U+009F) and with at least one character outside ECMA-262 whitespace (U+FEFF included), stored with the action only (never returned or audited). The pattern is ECMA-262 and ASCII only (`\\x` escapes and ECMA-262's `\\s`/`\\S`), so generated clients copy it verbatim; an engine whose `\\s` is not ECMA-262's (Python `re` leaves out U+FEFF) must use ECMA-262's set."
          },
          "idempotency_key": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]{16,64}$",
            "description": "Client-chosen key, unique per tenant (a UUID fits)."
          },
          "client_ts": {
            "type": "string",
            "maxLength": 64,
            "description": "When the operator acted, ISO 8601 with a zone offset; stored as given."
          }
        },
        "example": {
          "type": "override",
          "level": 2,
          "idempotency_key": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
          "client_ts": "2026-09-28T08:57:02+07:00"
        }
      },
      "FruitActionCommand": {
        "type": "object",
        "required": [
          "device_id",
          "command_id",
          "status",
          "reason"
        ],
        "additionalProperties": false,
        "description": "The re-measure's set_session outcome for one device of the fruit's session, as on allocation (SessionCommand), plus skipped with reason session_not_open when the session is not open (nothing is sent).",
        "properties": {
          "device_id": {
            "type": "string"
          },
          "command_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "enum": [
              "pending",
              "sent",
              "failed",
              "refused",
              "skipped"
            ]
          },
          "reason": {
            "enum": [
              "not_declared",
              "dispatch_failed",
              "device_not_found",
              "device_not_approved",
              "invalid_command",
              "session_not_open",
              null
            ],
            "x-sdk-enum": [
              "not_declared",
              "dispatch_failed",
              "device_not_found",
              "invalid_command",
              "session_not_open",
              null
            ]
          }
        }
      },
      "FruitActionResult": {
        "type": "object",
        "required": [
          "action",
          "fruit",
          "accepted_at",
          "measurement_round",
          "commands"
        ],
        "additionalProperties": false,
        "description": "The stored outcome of an action: the same body for the first request and every replay.",
        "properties": {
          "action": {
            "type": "object",
            "required": [
              "id",
              "type",
              "level",
              "client_ts",
              "created_at"
            ],
            "additionalProperties": false,
            "properties": {
              "id": {
                "type": "integer",
                "description": "Server id of the stored action."
              },
              "type": {
                "enum": [
                  "accept",
                  "remeasure",
                  "reject",
                  "override"
                ]
              },
              "level": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 1,
                "maximum": 4
              },
              "client_ts": {
                "type": "string"
              },
              "created_at": {
                "type": "number",
                "description": "Unix seconds (server time)."
              }
            }
          },
          "fruit": {
            "$ref": "#/components/schemas/Fruit"
          },
          "accepted_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds the fruit was first accepted into the lot (this round); null again once the bound measurement changes."
          },
          "measurement_round": {
            "type": "integer",
            "minimum": 0,
            "description": "Re-measures so far: 0 for the first measurement."
          },
          "commands": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/FruitActionCommand"
            },
            "description": "set_session per device of the session (re-measure only; empty otherwise)."
          }
        },
        "example": {
          "action": {
            "id": 41,
            "type": "override",
            "level": 2,
            "client_ts": "2026-09-28T08:57:02+07:00",
            "created_at": 1790560600.0
          },
          "fruit": {
            "tenant": "coop-dl",
            "code": "Q-014-0129",
            "n": 129,
            "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
            "lot": "LO-260928-014",
            "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
            "line": "A2",
            "operator": "user-7",
            "status": "overridden",
            "labels_printed_at": 1790000000.5,
            "created_at": 1790000000.5,
            "updated_at": 1790560600.0,
            "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
            "level": 2,
            "level_pred": 3,
            "maturity_class": "mature",
            "confidence": 0.91,
            "model": "sf100-m3",
            "measured_at": 1790560560.0,
            "weight_kg": 2.84,
            "level_sensory": 2,
            "override": true,
            "pending_review": false,
            "grade": "B",
            "eating_window": {
              "start_days": 4,
              "end_days": 6,
              "from_date": "2026-10-02",
              "to_date": "2026-10-04",
              "band": "ambient",
              "warning": null
            },
            "record_tier": "self_declared",
            "knock_envelope_id": "0b9c2f4e-7d1a-4c3e-9f8b-2a6d5e1c7b30",
            "scale_envelope_id": "6e3a1d9c-2b7f-4e8a-b5c4-9d0f1e2a3b47",
            "override_envelope_id": null
          },
          "accepted_at": null,
          "measurement_round": 0,
          "commands": []
        }
      },
      "EatingWindow": {
        "type": "object",
        "required": [
          "start_days",
          "end_days",
          "from_date",
          "to_date",
          "band",
          "warning"
        ],
        "additionalProperties": false,
        "description": "When the fruit is expected to be good to eat, counted from the measurement day in Asia/Ho_Chi_Minh; the row of the eating-window table for the effective level, the whole days since the lot's harvest date and the lot's storage band.",
        "properties": {
          "start_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 60
          },
          "end_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 60
          },
          "from_date": {
            "type": "string",
            "format": "date"
          },
          "to_date": {
            "type": "string",
            "format": "date"
          },
          "band": {
            "enum": [
              "ambient",
              "10-13C",
              "14-18C"
            ],
            "description": "Storage temperature band of the lot."
          },
          "warning": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "immature",
              "eat_soon",
              "overripe",
              null
            ]
          }
        },
        "example": {
          "start_days": 3,
          "end_days": 4,
          "from_date": "2026-10-01",
          "to_date": "2026-10-02",
          "band": "ambient",
          "warning": null
        }
      },
      "GradingRules": {
        "type": "object",
        "required": [
          "a_levels",
          "reject_levels",
          "a_weight_kg",
          "a_min_confidence",
          "eating_window"
        ],
        "additionalProperties": false,
        "description": "Grading rules of one variety. Grade: reject for a defect or a level in reject_levels; otherwise none until a level and a weight are known; A for a level in a_levels with the weight in an A band (inclusive), confidence at least a_min_confidence, nothing pending review and no sensory override conflict; else B. A level cannot be in both lists. The platform default (used for a variety without rules) is A levels [2, 3], reject levels [1, 4], A band 2.0-5.0 kg and confidence 0.8: placeholders until the buyer bands are known.",
        "properties": {
          "a_levels": {
            "type": "array",
            "items": {
              "type": "integer",
              "minimum": 1,
              "maximum": 4
            },
            "uniqueItems": true,
            "maxItems": 4,
            "minItems": 1
          },
          "reject_levels": {
            "type": "array",
            "items": {
              "type": "integer",
              "minimum": 1,
              "maximum": 4
            },
            "uniqueItems": true,
            "maxItems": 4,
            "minItems": 0
          },
          "a_weight_kg": {
            "type": "array",
            "minItems": 1,
            "maxItems": 8,
            "description": "[min, max] kg bands, 0 < min < max <= 100, strictly non-overlapping.",
            "items": {
              "type": "array",
              "minItems": 2,
              "maxItems": 2,
              "items": {
                "type": "number",
                "exclusiveMinimum": 0,
                "maximum": 100
              }
            }
          },
          "a_min_confidence": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
          },
          "eating_window": {
            "type": "array",
            "maxItems": 64,
            "description": "Rows of level x days since cut (min_days..max_days, inclusive) x band; rows of one level and band do not overlap.",
            "items": {
              "$ref": "#/components/schemas/EatingWindowRow"
            }
          }
        },
        "example": {
          "a_levels": [
            2,
            3
          ],
          "reject_levels": [
            1,
            4
          ],
          "a_weight_kg": [
            [
              2.0,
              5.0
            ]
          ],
          "a_min_confidence": 0.8,
          "eating_window": [
            {
              "band": "ambient",
              "end_days": 7,
              "level": 1,
              "max_days": 30,
              "min_days": 0,
              "start_days": 5,
              "warning": "immature"
            },
            {
              "band": "ambient",
              "end_days": 6,
              "level": 2,
              "max_days": 1,
              "min_days": 0,
              "start_days": 4,
              "warning": null
            },
            {
              "band": "ambient",
              "end_days": 4,
              "level": 2,
              "max_days": 3,
              "min_days": 2,
              "start_days": 3,
              "warning": null
            },
            {
              "band": "ambient",
              "end_days": 2,
              "level": 2,
              "max_days": 30,
              "min_days": 4,
              "start_days": 1,
              "warning": "eat_soon"
            },
            {
              "band": "ambient",
              "end_days": 4,
              "level": 3,
              "max_days": 1,
              "min_days": 0,
              "start_days": 3,
              "warning": null
            },
            {
              "band": "ambient",
              "end_days": 3,
              "level": 3,
              "max_days": 3,
              "min_days": 2,
              "start_days": 2,
              "warning": null
            },
            {
              "band": "ambient",
              "end_days": 1,
              "level": 3,
              "max_days": 30,
              "min_days": 4,
              "start_days": 0,
              "warning": "eat_soon"
            },
            {
              "band": "ambient",
              "end_days": 1,
              "level": 4,
              "max_days": 30,
              "min_days": 0,
              "start_days": 0,
              "warning": "overripe"
            },
            {
              "band": "14-18C",
              "end_days": 10,
              "level": 1,
              "max_days": 30,
              "min_days": 0,
              "start_days": 7,
              "warning": "immature"
            },
            {
              "band": "14-18C",
              "end_days": 8,
              "level": 2,
              "max_days": 30,
              "min_days": 0,
              "start_days": 5,
              "warning": null
            },
            {
              "band": "14-18C",
              "end_days": 6,
              "level": 3,
              "max_days": 30,
              "min_days": 0,
              "start_days": 4,
              "warning": null
            },
            {
              "band": "14-18C",
              "end_days": 2,
              "level": 4,
              "max_days": 30,
              "min_days": 0,
              "start_days": 0,
              "warning": "overripe"
            },
            {
              "band": "10-13C",
              "end_days": 12,
              "level": 1,
              "max_days": 30,
              "min_days": 0,
              "start_days": 9,
              "warning": "immature"
            },
            {
              "band": "10-13C",
              "end_days": 10,
              "level": 2,
              "max_days": 30,
              "min_days": 0,
              "start_days": 7,
              "warning": null
            },
            {
              "band": "10-13C",
              "end_days": 8,
              "level": 3,
              "max_days": 30,
              "min_days": 0,
              "start_days": 5,
              "warning": null
            },
            {
              "band": "10-13C",
              "end_days": 2,
              "level": 4,
              "max_days": 30,
              "min_days": 0,
              "start_days": 0,
              "warning": "overripe"
            }
          ]
        }
      },
      "EatingWindowRow": {
        "type": "object",
        "required": [
          "level",
          "min_days",
          "max_days",
          "band",
          "start_days",
          "end_days",
          "warning"
        ],
        "additionalProperties": false,
        "properties": {
          "level": {
            "type": "integer",
            "minimum": 1,
            "maximum": 4
          },
          "min_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 365
          },
          "max_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 365
          },
          "band": {
            "enum": [
              "ambient",
              "10-13C",
              "14-18C"
            ]
          },
          "start_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 60
          },
          "end_days": {
            "type": "integer",
            "minimum": 0,
            "maximum": 60
          },
          "warning": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "immature",
              "eat_soon",
              "overripe",
              null
            ]
          }
        },
        "example": {
          "band": "ambient",
          "end_days": 4,
          "level": 3,
          "max_days": 1,
          "min_days": 0,
          "start_days": 3,
          "warning": null
        }
      },
      "GradingRule": {
        "type": "object",
        "required": [
          "id",
          "tenant",
          "variety",
          "rules",
          "updated_at",
          "updated_by"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer",
            "description": "Server id (the audit entity id)."
          },
          "tenant": {
            "type": "string"
          },
          "variety": {
            "type": "string",
            "description": "The lot variety these rules apply to."
          },
          "rules": {
            "$ref": "#/components/schemas/GradingRules"
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_by": {
            "type": "string",
            "description": "The principal that last wrote them."
          }
        },
        "example": {
          "id": 3,
          "tenant": "coop-dl",
          "variety": "Ri6",
          "rules": {
            "a_levels": [
              2,
              3
            ],
            "reject_levels": [
              1,
              4
            ],
            "a_weight_kg": [
              [
                2.0,
                5.0
              ]
            ],
            "a_min_confidence": 0.8,
            "eating_window": [
              {
                "band": "ambient",
                "end_days": 7,
                "level": 1,
                "max_days": 30,
                "min_days": 0,
                "start_days": 5,
                "warning": "immature"
              },
              {
                "band": "ambient",
                "end_days": 6,
                "level": 2,
                "max_days": 1,
                "min_days": 0,
                "start_days": 4,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 4,
                "level": 2,
                "max_days": 3,
                "min_days": 2,
                "start_days": 3,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 2,
                "level": 2,
                "max_days": 30,
                "min_days": 4,
                "start_days": 1,
                "warning": "eat_soon"
              },
              {
                "band": "ambient",
                "end_days": 4,
                "level": 3,
                "max_days": 1,
                "min_days": 0,
                "start_days": 3,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 3,
                "level": 3,
                "max_days": 3,
                "min_days": 2,
                "start_days": 2,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 1,
                "level": 3,
                "max_days": 30,
                "min_days": 4,
                "start_days": 0,
                "warning": "eat_soon"
              },
              {
                "band": "ambient",
                "end_days": 1,
                "level": 4,
                "max_days": 30,
                "min_days": 0,
                "start_days": 0,
                "warning": "overripe"
              },
              {
                "band": "14-18C",
                "end_days": 10,
                "level": 1,
                "max_days": 30,
                "min_days": 0,
                "start_days": 7,
                "warning": "immature"
              },
              {
                "band": "14-18C",
                "end_days": 8,
                "level": 2,
                "max_days": 30,
                "min_days": 0,
                "start_days": 5,
                "warning": null
              },
              {
                "band": "14-18C",
                "end_days": 6,
                "level": 3,
                "max_days": 30,
                "min_days": 0,
                "start_days": 4,
                "warning": null
              },
              {
                "band": "14-18C",
                "end_days": 2,
                "level": 4,
                "max_days": 30,
                "min_days": 0,
                "start_days": 0,
                "warning": "overripe"
              },
              {
                "band": "10-13C",
                "end_days": 12,
                "level": 1,
                "max_days": 30,
                "min_days": 0,
                "start_days": 9,
                "warning": "immature"
              },
              {
                "band": "10-13C",
                "end_days": 10,
                "level": 2,
                "max_days": 30,
                "min_days": 0,
                "start_days": 7,
                "warning": null
              },
              {
                "band": "10-13C",
                "end_days": 8,
                "level": 3,
                "max_days": 30,
                "min_days": 0,
                "start_days": 5,
                "warning": null
              },
              {
                "band": "10-13C",
                "end_days": 2,
                "level": 4,
                "max_days": 30,
                "min_days": 0,
                "start_days": 0,
                "warning": "overripe"
              }
            ]
          },
          "updated_at": 1790000000.5,
          "updated_by": "admin@coop.example"
        }
      },
      "GradingRulePage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor",
          "platform_default"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/GradingRule"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          },
          "platform_default": {
            "$ref": "#/components/schemas/GradingRules",
            "description": "The platform default rules, normalized: what a variety without rules of its own (and a lot without a variety) is graded with. An editor starts a new variety from it."
          }
        }
      },
      "SessionFeedItem": {
        "type": "object",
        "description": "One fruit upsert: the fruit as it is now and the rx_seq of its latest change.",
        "required": [
          "rx_seq",
          "fruit"
        ],
        "additionalProperties": false,
        "properties": {
          "rx_seq": {
            "type": "integer",
            "minimum": 1
          },
          "fruit": {
            "$ref": "#/components/schemas/Fruit"
          }
        }
      },
      "SessionFeed": {
        "type": "object",
        "required": [
          "items",
          "next_after",
          "session_status",
          "devices",
          "scale",
          "pending"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SessionFeedItem"
            }
          },
          "next_after": {
            "type": "integer",
            "minimum": 0,
            "description": "The rx_seq of the last item, or the given `after` when there is none."
          },
          "session_status": {
            "type": "string",
            "enum": [
              "open",
              "paused",
              "closed"
            ]
          },
          "devices": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Device"
            },
            "description": "The devices stored on the session, by id."
          },
          "scale": {
            "oneOf": [
              {
                "type": "null"
              },
              {
                "type": "object",
                "required": [
                  "device_id",
                  "weight_kg",
                  "at"
                ],
                "additionalProperties": false,
                "properties": {
                  "device_id": {
                    "type": "string"
                  },
                  "weight_kg": {
                    "type": "number"
                  },
                  "at": {
                    "type": "number",
                    "description": "Event time of the reading, Unix seconds."
                  }
                }
              }
            ],
            "description": "Scale live weight: the newest `mass.net` reading of the session's devices, or null."
          },
          "pending": {
            "type": "object",
            "required": [
              "awaiting_device",
              "pending_review"
            ],
            "additionalProperties": false,
            "properties": {
              "awaiting_device": {
                "type": "integer",
                "minimum": 0
              },
              "pending_review": {
                "type": "integer",
                "minimum": 0
              }
            },
            "description": "Fruits of the session still awaiting a device, and those under review."
          }
        }
      },
      "LotSummary": {
        "type": "object",
        "required": [
          "lot",
          "status",
          "count",
          "awaiting_device",
          "rejected_unmeasured",
          "kg",
          "weighed",
          "levels",
          "grades",
          "overrides",
          "avg_confidence",
          "pending_review",
          "export",
          "volume"
        ],
        "additionalProperties": false,
        "properties": {
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "status": {
            "type": "string",
            "enum": [
              "draft",
              "open",
              "paused",
              "closed",
              "packed",
              "shipped",
              "recalled",
              "withdrawn"
            ]
          },
          "count": {
            "type": "integer",
            "minimum": 0,
            "description": "Fruits with a device record: status recorded or overridden, or rejected with at least one bound device envelope (knock, scale or override). Fruits awaiting a device and fruits rejected before any measurement are reported apart."
          },
          "awaiting_device": {
            "type": "integer",
            "minimum": 0,
            "description": "Fruits labelled but without a device record yet."
          },
          "rejected_unmeasured": {
            "type": "integer",
            "minimum": 0,
            "description": "Fruits rejected before any device envelope was bound (no device record); not in `count`, `levels` or `grades`."
          },
          "kg": {
            "type": "number",
            "minimum": 0,
            "description": "Sum of the scale weights of the counted fruits, rounded to 3 decimals."
          },
          "weighed": {
            "type": "integer",
            "minimum": 0,
            "description": "Counted fruits that have a scale weight."
          },
          "levels": {
            "type": "object",
            "required": [
              "1",
              "2",
              "3",
              "4",
              "unknown"
            ],
            "additionalProperties": false,
            "properties": {
              "1": {
                "type": "integer",
                "minimum": 0
              },
              "2": {
                "type": "integer",
                "minimum": 0
              },
              "3": {
                "type": "integer",
                "minimum": 0
              },
              "4": {
                "type": "integer",
                "minimum": 0
              },
              "unknown": {
                "type": "integer",
                "minimum": 0
              }
            },
            "description": "Counted fruits per effective ripeness level (the sensory level when overridden, else the device level); `unknown` without a level."
          },
          "grades": {
            "type": "object",
            "required": [
              "A",
              "B",
              "reject",
              "ungraded"
            ],
            "additionalProperties": false,
            "properties": {
              "A": {
                "type": "integer",
                "minimum": 0
              },
              "B": {
                "type": "integer",
                "minimum": 0
              },
              "reject": {
                "type": "integer",
                "minimum": 0
              },
              "ungraded": {
                "type": "integer",
                "minimum": 0
              }
            },
            "description": "Counted fruits per grade; a fruit with status rejected counts as reject."
          },
          "overrides": {
            "type": "integer",
            "minimum": 0,
            "description": "Counted fruits with a sensory override."
          },
          "avg_confidence": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 1,
            "description": "Mean device confidence of the counted fruits that have one, 4 decimals; null when none has one."
          },
          "pending_review": {
            "type": "integer",
            "minimum": 0,
            "description": "Fruits of the lot with a bound envelope still in quarantine."
          },
          "export": {
            "type": "object",
            "required": [
              "count",
              "kg"
            ],
            "additionalProperties": false,
            "properties": {
              "count": {
                "type": "integer",
                "minimum": 0
              },
              "kg": {
                "type": "number",
                "minimum": 0
              }
            },
            "description": "Counted fruits graded A or B and not rejected, and their weight."
          },
          "volume": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/GrowingAreaVolume"
              },
              {
                "type": "null"
              }
            ],
            "description": "Volume headroom of the lot's growing area for the season of its harvest date (as GET /v1/growing-areas/{code}/volume); null when the lot has no growing area."
          }
        },
        "description": "Lot summary (L6, #31)."
      },
      "PublicCode": {
        "type": "string",
        "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"
      },
      "PublicText": {
        "type": "string",
        "minLength": 1,
        "maxLength": 200
      },
      "PublicIsoDate": {
        "type": "string",
        "format": "date",
        "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
      },
      "PublicIsoDateTime": {
        "type": "string",
        "format": "date-time",
        "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]+)?)?(Z|[+-][0-9]{2}:[0-9]{2})$"
      },
      "PublicSameOriginPath": {
        "type": "string",
        "maxLength": 512,
        "pattern": "^/(?![/\\\\])[!-\\[\\]-~]*$"
      },
      "PublicTrustTier": {
        "type": "string",
        "enum": [
          "self_declared",
          "device_recorded",
          "cross_checked",
          "lab_verified"
        ]
      },
      "PublicStatus": {
        "type": "string",
        "enum": [
          "normal",
          "recalled",
          "withdrawn",
          "on_hold",
          "under_review"
        ]
      },
      "PublicEvidenceSource": {
        "type": "string",
        "enum": [
          "manual",
          "registered_app",
          "device",
          "lab",
          "registry",
          "logger"
        ]
      },
      "PublicPeriod": {
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "precision",
              "start",
              "end"
            ],
            "properties": {
              "precision": {
                "const": "day"
              },
              "start": {
                "$ref": "#/components/schemas/PublicIsoDate"
              },
              "end": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "precision",
              "start",
              "end"
            ],
            "properties": {
              "precision": {
                "const": "minute"
              },
              "start": {
                "$ref": "#/components/schemas/PublicIsoDateTime"
              },
              "end": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicIsoDateTime"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          }
        ]
      },
      "PublicAnalyte": {
        "type": "string",
        "enum": [
          "cadmium",
          "auramine_o",
          "origin_isotopes"
        ]
      },
      "PublicLabLimit": {
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "value"
            ],
            "properties": {
              "kind": {
                "const": "max"
              },
              "value": {
                "type": "number",
                "minimum": 0
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind"
            ],
            "properties": {
              "kind": {
                "const": "banned"
              }
            }
          }
        ]
      },
      "PublicLabResult": {
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "analyte",
              "outcome",
              "value",
              "unit",
              "limit",
              "pass"
            ],
            "properties": {
              "analyte": {
                "$ref": "#/components/schemas/PublicAnalyte"
              },
              "outcome": {
                "const": "measured"
              },
              "value": {
                "type": "number",
                "minimum": 0
              },
              "unit": {
                "type": "string",
                "minLength": 1,
                "maxLength": 16
              },
              "limit": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicLabLimit"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "pass": {
                "type": "boolean"
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "analyte",
              "outcome",
              "limit",
              "pass"
            ],
            "properties": {
              "analyte": {
                "$ref": "#/components/schemas/PublicAnalyte"
              },
              "outcome": {
                "const": "not_detected"
              },
              "limit": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicLabLimit"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "pass": {
                "type": "boolean"
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "analyte",
              "outcome",
              "matched_region",
              "pass"
            ],
            "properties": {
              "analyte": {
                "$ref": "#/components/schemas/PublicAnalyte"
              },
              "outcome": {
                "const": "origin_match"
              },
              "matched_region": {
                "$ref": "#/components/schemas/PublicText"
              },
              "pass": {
                "type": "boolean"
              }
            }
          }
        ]
      },
      "PublicMarket": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "country_code",
          "short_name",
          "authority"
        ],
        "properties": {
          "country_code": {
            "type": "string",
            "pattern": "^[A-Z]{2}$"
          },
          "short_name": {
            "$ref": "#/components/schemas/PublicText"
          },
          "authority": {
            "$ref": "#/components/schemas/PublicText"
          }
        }
      },
      "PublicDownloads": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "epcis_url",
          "credential_url"
        ],
        "properties": {
          "epcis_url": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicSameOriginPath"
              },
              {
                "type": "null"
              }
            ]
          },
          "credential_url": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicSameOriginPath"
              },
              {
                "type": "null"
              }
            ],
            "description": "X3 (#44): the fruit's UNTP credential (`GET /v1/public/fruits/{publicId}/credential`), present when the fruit's lot was sealed with public documents and its issuer key is not revoked; null otherwise. A fruit's `epcis_url` stays null: its events are in its lot's document, which the credential links."
          }
        }
      },
      "PublicLotDownloads": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "epcis_url",
          "credential_url",
          "customs_dossier_url"
        ],
        "properties": {
          "epcis_url": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicSameOriginPath"
              },
              {
                "type": "null"
              }
            ],
            "description": "X3 (#44): the lot's EPCIS 2.0 document (`GET /v1/public/lots/{publicId}/epcis.jsonld`), present once the lot was sealed with public documents; null otherwise."
          },
          "credential_url": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicSameOriginPath"
              },
              {
                "type": "null"
              }
            ],
            "description": "X3 (#44): the lot's UNTP credential (`GET /v1/public/lots/{publicId}/credential`), present when the lot was sealed with public documents, its issuer key is not revoked and the lab key its conformity claims cite is not revoked for compromise; null otherwise (then `issuer` is null too)."
          },
          "customs_dossier_url": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicSameOriginPath"
              },
              {
                "type": "null"
              }
            ],
            "description": "X4 (#45): the HTML print view of the lot's code file for China customs (its customs dossier, `GET /v1/public/lots/{publicId}/customs-dossier/print?lang=…`), present only for a packed lot on a shipment to the CN market; null otherwise."
          }
        }
      },
      "PublicCustomsDossier": {
        "type": "object",
        "additionalProperties": false,
        "description": "X4 (#45): the code file for China customs (the customs dossier) of a public lot that is packed (so sealed, L8 #33) and on a shipment to the CN market. `sealed` holds the lot, carton and registry facts frozen when the lot was packed (their members depend on `format`: a lot packed since addresses are coded by official administrative unit codes, with its packing house or growing area coded, has format 2, #273), and `seal` their SHA-256 seal digest recorded then, so a registry edit after packing never changes the dossier. The rest is projected from the lot's public record (PublicLot), except `producer`, the lot's company as its company profile names it now (#186). No field outside the Public Data Allowlist appears: no GACC registration value, seal number, coordinates, grower, container or device. The growing-area and packing-house codes are the tenant's registry entries on the platform (`registry_entry` gives their tier and source), not GACC registration numbers. The body is the RFC 8785 JSON Canonicalization Scheme (JCS) form of the document, in UTF-8: no whitespace, members sorted by the UTF-16 code units of their names, strings escaped as ECMAScript's JSON.stringify does and numbers in ECMAScript's Number-to-String form (0.00001, not 1e-05; 12, not 12.0). It holds no per-read value and is byte-identical for the same stored facts; `digest.value` is the SHA-256 (hex) of the JCS form of the document without `digest`.",
        "required": [
          "format",
          "lang",
          "status",
          "trust_tier",
          "public_id",
          "origin_country",
          "sealed",
          "seal",
          "registry_entry",
          "lab_report",
          "shipment",
          "protocol",
          "producer",
          "digest"
        ],
        "properties": {
          "format": {
            "type": "string",
            "enum": [
              "agritrace-customs-dossier/1",
              "agritrace-customs-dossier/2"
            ],
            "description": "The format of the document, that of its sealed record: `agritrace-customs-dossier/1` for a lot packed before addresses were coded by official administrative unit codes, or since then with neither its packing house nor its growing area coded (its `sealed` facts name the district), `agritrace-customs-dossier/2` for a lot packed since then with its packing house or growing area coded (#273: Viet Nam has had no district level since 1 July 2025; its `sealed` facts name the commune and province with their official codes and `admin_units_version`). A document keeps its format for good. Only `sealed` differs between the two: a consumer that reads its members switches on `format`; the seal digest is checked the same way in both.",
            "x-sdk-object": {
              "type": "string",
              "enum": [
                "agritrace-customs-dossier/1"
              ]
            }
          },
          "lang": {
            "type": "string",
            "enum": [
              "vi",
              "zh-Hans",
              "en"
            ]
          },
          "status": {
            "$ref": "#/components/schemas/PublicStatus"
          },
          "trust_tier": {
            "$ref": "#/components/schemas/PublicTrustTier"
          },
          "public_id": {
            "$ref": "#/components/schemas/PublicCode"
          },
          "origin_country": {
            "$ref": "#/components/schemas/PublicText"
          },
          "sealed": {
            "description": "The lot, carton and registry facts frozen when the lot was packed, exactly as stored: a registry edit after packing never changes them. `seal.value` is the SHA-256 of their JCS form, whatever the format. Their members depend on `format` (#273): format 1 names the district, format 2 the commune and province with their official codes. The locality parts are the lot page's localities, unjoined.",
            "oneOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "lot",
                  "cartons",
                  "growing_area",
                  "packing_house",
                  "durian_protocol"
                ],
                "properties": {
                  "lot": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "code",
                      "product",
                      "variety",
                      "harvested_on",
                      "packed_on"
                    ],
                    "properties": {
                      "code": {
                        "$ref": "#/components/schemas/PublicCode"
                      },
                      "product": {
                        "type": "string",
                        "enum": [
                          "durian"
                        ]
                      },
                      "variety": {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      "harvested_on": {
                        "$ref": "#/components/schemas/PublicIsoDate"
                      },
                      "packed_on": {
                        "$ref": "#/components/schemas/PublicIsoDate"
                      }
                    }
                  },
                  "cartons": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "count",
                      "fruit_count",
                      "net_mass_kg"
                    ],
                    "properties": {
                      "count": {
                        "type": "integer",
                        "minimum": 0
                      },
                      "fruit_count": {
                        "type": "integer",
                        "minimum": 0
                      },
                      "net_mass_kg": {
                        "type": "number",
                        "minimum": 0
                      }
                    }
                  },
                  "growing_area": {
                    "oneOf": [
                      {
                        "type": "object",
                        "additionalProperties": false,
                        "required": [
                          "code",
                          "commune",
                          "district"
                        ],
                        "properties": {
                          "code": {
                            "$ref": "#/components/schemas/PublicCode"
                          },
                          "commune": {
                            "oneOf": [
                              {
                                "$ref": "#/components/schemas/PublicText"
                              },
                              {
                                "type": "null"
                              }
                            ]
                          },
                          "district": {
                            "oneOf": [
                              {
                                "$ref": "#/components/schemas/PublicText"
                              },
                              {
                                "type": "null"
                              }
                            ]
                          }
                        }
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "packing_house": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "code",
                      "name",
                      "district",
                      "province"
                    ],
                    "properties": {
                      "code": {
                        "$ref": "#/components/schemas/PublicCode"
                      },
                      "name": {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      "district": {
                        "oneOf": [
                          {
                            "$ref": "#/components/schemas/PublicText"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "province": {
                        "oneOf": [
                          {
                            "$ref": "#/components/schemas/PublicText"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      }
                    }
                  },
                  "durian_protocol": {
                    "type": "boolean",
                    "description": "Whether the Durian Protocol applied when the lot was packed: a GACC code on a durian growing area, for a durian lot (the flag only; the code is never published)."
                  }
                },
                "description": "Format 1 (`agritrace-customs-dossier/1`): the growing area's commune and district, the packing house's district and province, as the registry held them when the lot was packed."
              },
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "lot",
                  "cartons",
                  "growing_area",
                  "packing_house",
                  "admin_units_version",
                  "durian_protocol"
                ],
                "description": "Format 2 (`agritrace-customs-dossier/2`, #273): the growing area's and the packing house's commune and province, each with its official code, and the version of the official list of administrative units the codes come from. The names are the official ones for a record coded by official codes; a record not coded yet when the lot was packed has its text and null codes.",
                "properties": {
                  "lot": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "code",
                      "product",
                      "variety",
                      "harvested_on",
                      "packed_on"
                    ],
                    "properties": {
                      "code": {
                        "$ref": "#/components/schemas/PublicCode"
                      },
                      "product": {
                        "type": "string",
                        "enum": [
                          "durian"
                        ]
                      },
                      "variety": {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      "harvested_on": {
                        "$ref": "#/components/schemas/PublicIsoDate"
                      },
                      "packed_on": {
                        "$ref": "#/components/schemas/PublicIsoDate"
                      }
                    }
                  },
                  "cartons": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "count",
                      "fruit_count",
                      "net_mass_kg"
                    ],
                    "properties": {
                      "count": {
                        "type": "integer",
                        "minimum": 0
                      },
                      "fruit_count": {
                        "type": "integer",
                        "minimum": 0
                      },
                      "net_mass_kg": {
                        "type": "number",
                        "minimum": 0
                      }
                    }
                  },
                  "growing_area": {
                    "oneOf": [
                      {
                        "type": "object",
                        "additionalProperties": false,
                        "required": [
                          "code",
                          "commune",
                          "commune_code",
                          "province",
                          "province_code"
                        ],
                        "properties": {
                          "code": {
                            "$ref": "#/components/schemas/PublicCode"
                          },
                          "commune": {
                            "oneOf": [
                              {
                                "$ref": "#/components/schemas/PublicText"
                              },
                              {
                                "type": "null"
                              }
                            ]
                          },
                          "commune_code": {
                            "oneOf": [
                              {
                                "type": "string",
                                "pattern": "^[0-9]{5}$"
                              },
                              {
                                "type": "null"
                              }
                            ],
                            "description": "The official commune code (#273), null when the record was not coded when the lot was packed."
                          },
                          "province": {
                            "oneOf": [
                              {
                                "$ref": "#/components/schemas/PublicText"
                              },
                              {
                                "type": "null"
                              }
                            ]
                          },
                          "province_code": {
                            "oneOf": [
                              {
                                "type": "string",
                                "pattern": "^[0-9]{2}$"
                              },
                              {
                                "type": "null"
                              }
                            ],
                            "description": "The official province code (#273), null when the record was not coded when the lot was packed."
                          }
                        }
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "packing_house": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "code",
                      "name",
                      "commune",
                      "commune_code",
                      "province",
                      "province_code"
                    ],
                    "properties": {
                      "code": {
                        "$ref": "#/components/schemas/PublicCode"
                      },
                      "name": {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      "commune": {
                        "oneOf": [
                          {
                            "$ref": "#/components/schemas/PublicText"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "commune_code": {
                        "oneOf": [
                          {
                            "type": "string",
                            "pattern": "^[0-9]{5}$"
                          },
                          {
                            "type": "null"
                          }
                        ],
                        "description": "The official commune code (#273), null when the record was not coded when the lot was packed."
                      },
                      "province": {
                        "oneOf": [
                          {
                            "$ref": "#/components/schemas/PublicText"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "province_code": {
                        "oneOf": [
                          {
                            "type": "string",
                            "pattern": "^[0-9]{2}$"
                          },
                          {
                            "type": "null"
                          }
                        ],
                        "description": "The official province code (#273), null when the record was not coded when the lot was packed."
                      }
                    }
                  },
                  "admin_units_version": {
                    "oneOf": [
                      {
                        "type": "string",
                        "pattern": "^vn-[0-9]{4}-[0-9]{2}-[0-9]{2}$"
                      },
                      {
                        "type": "null"
                      }
                    ],
                    "description": "The version of the official list of administrative units the codes come from (for example `vn-2026-10-17`; a code is only meaningful with its version). Always set: a format-2 record has its packing house or its growing area coded (a lot with neither coded has a format-1 record)."
                  },
                  "durian_protocol": {
                    "type": "boolean",
                    "description": "Whether the Durian Protocol applied when the lot was packed: a GACC code on a durian growing area, for a durian lot (the flag only; the code is never published)."
                  }
                }
              }
            ],
            "x-sdk-object": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "lot",
                "cartons",
                "growing_area",
                "packing_house",
                "durian_protocol"
              ],
              "description": "The lot, carton and registry facts frozen when the lot was packed (the pack event, `lot_sealed_records`), exactly as stored: a registry edit after packing never changes them. `seal.value` is the SHA-256 of their JCS form. The locality parts are the lot page's localities, unjoined.",
              "properties": {
                "lot": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "product",
                    "variety",
                    "harvested_on",
                    "packed_on"
                  ],
                  "properties": {
                    "code": {
                      "$ref": "#/components/schemas/PublicCode"
                    },
                    "product": {
                      "type": "string",
                      "enum": [
                        "durian"
                      ]
                    },
                    "variety": {
                      "$ref": "#/components/schemas/PublicText"
                    },
                    "harvested_on": {
                      "$ref": "#/components/schemas/PublicIsoDate"
                    },
                    "packed_on": {
                      "$ref": "#/components/schemas/PublicIsoDate"
                    }
                  }
                },
                "cartons": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "count",
                    "fruit_count",
                    "net_mass_kg"
                  ],
                  "properties": {
                    "count": {
                      "type": "integer",
                      "minimum": 0
                    },
                    "fruit_count": {
                      "type": "integer",
                      "minimum": 0
                    },
                    "net_mass_kg": {
                      "type": "number",
                      "minimum": 0
                    }
                  }
                },
                "growing_area": {
                  "oneOf": [
                    {
                      "type": "object",
                      "additionalProperties": false,
                      "required": [
                        "code",
                        "commune",
                        "district"
                      ],
                      "properties": {
                        "code": {
                          "$ref": "#/components/schemas/PublicCode"
                        },
                        "commune": {
                          "oneOf": [
                            {
                              "$ref": "#/components/schemas/PublicText"
                            },
                            {
                              "type": "null"
                            }
                          ]
                        },
                        "district": {
                          "oneOf": [
                            {
                              "$ref": "#/components/schemas/PublicText"
                            },
                            {
                              "type": "null"
                            }
                          ]
                        }
                      }
                    },
                    {
                      "type": "null"
                    }
                  ]
                },
                "packing_house": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "name",
                    "district",
                    "province"
                  ],
                  "properties": {
                    "code": {
                      "$ref": "#/components/schemas/PublicCode"
                    },
                    "name": {
                      "$ref": "#/components/schemas/PublicText"
                    },
                    "district": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/PublicText"
                        },
                        {
                          "type": "null"
                        }
                      ]
                    },
                    "province": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/PublicText"
                        },
                        {
                          "type": "null"
                        }
                      ]
                    }
                  }
                },
                "durian_protocol": {
                  "type": "boolean",
                  "description": "Whether the Durian Protocol applied when the lot was packed: a GACC code on a durian growing area, for a durian lot (the flag only; the code is never published)."
                }
              }
            }
          },
          "seal": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "algorithm",
              "value",
              "basis"
            ],
            "description": "The seal digest recorded when the lot was packed: the SHA-256 (hex) of the JCS form of `sealed`. `basis` is `transition` when it was taken in the pack transaction, `migration` when the lot was packed before sealed records existed and its facts were captured from the registry when the platform was upgraded.",
            "properties": {
              "algorithm": {
                "type": "string",
                "enum": [
                  "sha-256"
                ]
              },
              "value": {
                "type": "string",
                "pattern": "^[0-9a-f]{64}$"
              },
              "basis": {
                "type": "string",
                "enum": [
                  "transition",
                  "migration"
                ]
              }
            }
          },
          "registry_entry": {
            "oneOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "tier",
                  "source"
                ],
                "properties": {
                  "tier": {
                    "$ref": "#/components/schemas/PublicTrustTier"
                  },
                  "source": {
                    "$ref": "#/components/schemas/PublicEvidenceSource"
                  }
                }
              },
              {
                "type": "null"
              }
            ],
            "description": "The trust tier and source of the growing-area and packing-house codes: those of the lot's registration step (PublicLotJourneyStep `registration`; Self-declared from the tenant's own registry entry until a signed or registry source exists, L8 #33), or null when the lot has no growing area. The codes are the tenant's entries on the platform, not GACC orchard (PUC) or packing-house (PHC) registration numbers."
          },
          "lab_report": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "report_number",
              "signed_at",
              "key_custody",
              "market_approval",
              "results"
            ],
            "properties": {
              "report_number": {
                "$ref": "#/components/schemas/PublicCode"
              },
              "signed_at": {
                "$ref": "#/components/schemas/PublicIsoDateTime"
              },
              "key_custody": {
                "enum": [
                  "lab",
                  "server"
                ],
                "description": "Who holds the key that signed the report (#73), as on the public lot page: `lab`, the lab itself; `server`, CropPath, which signed a lab portal entry on the lab's behalf with the key it holds for the lab (never the lab's own signature; the print view says so)."
              },
              "market_approval": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicLabMarketApproval"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "#154, as on the public lot page: whether the lab was on the approved list of the report's market for every tested analyte on the signed date, with the approval's reference; the print view states it, or that the lab is not on the list, so the results cannot count as Lab-verified for that market (naming no tier they reach)."
              },
              "results": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/PublicLabResult"
                },
                "minItems": 1,
                "maxItems": 32
              }
            }
          },
          "shipment": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "market",
              "border_gate",
              "exported_on"
            ],
            "properties": {
              "market": {
                "$ref": "#/components/schemas/PublicMarket"
              },
              "border_gate": {
                "$ref": "#/components/schemas/PublicText"
              },
              "exported_on": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          "protocol": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicText"
              },
              {
                "type": "null"
              }
            ],
            "description": "The Durian Protocol's name in `lang` when `sealed.durian_protocol` is true, else null."
          },
          "producer": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/CompanyProducer"
              },
              {
                "type": "null"
              }
            ],
            "description": "#186: the lot's company as its company profile names it now (legal name and address), null until the company saves a profile. Not part of `sealed`: a profile edit changes this member and `digest`, never `sealed` or `seal`."
          },
          "digest": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "algorithm",
              "value"
            ],
            "properties": {
              "algorithm": {
                "type": "string",
                "enum": [
                  "sha-256"
                ]
              },
              "value": {
                "type": "string",
                "pattern": "^[0-9a-f]{64}$"
              }
            }
          }
        },
        "x-sdk-description": "X4 (#45): the code file for China customs (the customs dossier) of a public lot that is packed (so sealed, L8 #33) and on a shipment to the CN market. `sealed` holds the lot, carton and registry facts frozen when the lot was packed, and `seal` their SHA-256 seal digest recorded then, so a registry edit after packing never changes the dossier. The rest is projected from the lot's public record (PublicLot), except `producer`, the lot's company as its company profile names it now (#186). No field outside the Public Data Allowlist appears: no GACC registration value, seal number, coordinates, grower, container or device. The growing-area and packing-house codes are the tenant's registry entries on the platform (`registry_entry` gives their tier and source), not GACC registration numbers. The body is the RFC 8785 JSON Canonicalization Scheme (JCS) form of the document, in UTF-8: no whitespace, members sorted by the UTF-16 code units of their names, strings escaped as ECMAScript's JSON.stringify does and numbers in ECMAScript's Number-to-String form (0.00001, not 1e-05; 12, not 12.0). It holds no per-read value and is byte-identical for the same stored facts; `digest.value` is the SHA-256 (hex) of the JCS form of the document without `digest`."
      },
      "PublicIssuer": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "did",
          "key_id"
        ],
        "properties": {
          "did": {
            "type": "string",
            "pattern": "^did:web:[A-Za-z0-9.%:_-]{1,200}$"
          },
          "key_id": {
            "type": "string",
            "maxLength": 260
          }
        }
      },
      "PublicSatelliteCheck": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "source",
          "image_date",
          "area_matches_registration",
          "deforestation_detected"
        ],
        "properties": {
          "source": {
            "$ref": "#/components/schemas/PublicText"
          },
          "image_date": {
            "$ref": "#/components/schemas/PublicIsoDate"
          },
          "area_matches_registration": {
            "type": "boolean"
          },
          "deforestation_detected": {
            "type": "boolean"
          }
        }
      },
      "PublicLotJourneyStep": {
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "protocol",
              "coordinates_declared",
              "sources",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "registration"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "protocol": {
                "description": "Localised name of the Durian Protocol, only when the growing area has a GACC growing-area (PUC) code, its crop is durian and the lot's product is durian; null otherwise (L8, #33).",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "coordinates_declared": {
                "description": "Whether the growing area's plot coordinates (its polygon) were declared; the coordinates themselves are never published (L8, #33).",
                "type": "boolean"
              },
              "sources": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/PublicText"
                },
                "minItems": 1,
                "maxItems": 8
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "harvest_mass_kg",
              "satellite",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "harvest"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "harvest_mass_kg": {
                "type": "number",
                "minimum": 0
              },
              "satellite": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicSatelliteCheck"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "device",
              "measured_count",
              "rejected_count",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "measurement"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "device": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "model",
                  "serial",
                  "model_version"
                ],
                "properties": {
                  "model": {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  "serial": {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  "model_version": {
                    "$ref": "#/components/schemas/PublicText"
                  }
                }
              },
              "measured_count": {
                "type": "integer",
                "minimum": 0
              },
              "rejected_count": {
                "type": "integer",
                "minimum": 0
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "sample_count",
              "lab_code",
              "analytes",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "lab"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "sample_count": {
                "type": "integer",
                "minimum": 0
              },
              "lab_code": {
                "$ref": "#/components/schemas/PublicCode"
              },
              "analytes": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/PublicAnalyte"
                },
                "minItems": 1
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "carton_count",
              "fruit_count",
              "net_mass_kg",
              "seal_number",
              "shipped_mass_kg",
              "harvest_mass_kg",
              "uncartoned_fruit_count",
              "uncartoned_mass_kg",
              "gs1_digital_link",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "packing"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "carton_count": {
                "type": "integer",
                "minimum": 0
              },
              "fruit_count": {
                "type": "integer",
                "minimum": 0
              },
              "net_mass_kg": {
                "type": "number",
                "minimum": 0
              },
              "seal_number": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicCode"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "shipped_mass_kg": {
                "type": [
                  "number",
                  "null"
                ],
                "minimum": 0,
                "description": "Mass the growing area has shipped so far (its packed lots of the season, across tenants); null, with the harvest, when the lot has no growing area (#37)."
              },
              "harvest_mass_kg": {
                "type": [
                  "number",
                  "null"
                ],
                "minimum": 0,
                "description": "The growing area's declared harvest for the season; null when none is declared (#37)."
              },
              "uncartoned_fruit_count": {
                "type": "integer",
                "minimum": 0,
                "description": "The lot's exportable fruits (L6's export) left out of every carton; 0 when every one is cartoned (#37)."
              },
              "uncartoned_mass_kg": {
                "type": "number",
                "minimum": 0,
                "description": "Their measured mass; 0 when every exportable fruit is cartoned (#37)."
              },
              "gs1_digital_link": {
                "type": "boolean",
                "description": "The lot has a GTIN and a lot code of at most 20 characters (GS1 AI 10), so each carton's QR label is a GS1 Digital Link; false: the page leaves that clause out (#37)."
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "border_gate",
              "setpoint_c",
              "logger_interval_minutes",
              "logger_check",
              "export_filed",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "shipping"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "border_gate": {
                "$ref": "#/components/schemas/PublicText"
              },
              "setpoint_c": {
                "type": "number"
              },
              "logger_interval_minutes": {
                "type": "integer",
                "minimum": 0
              },
              "logger_check": {
                "type": "string",
                "enum": [
                  "matched",
                  "incomplete",
                  "out_of_range",
                  "missing"
                ],
                "description": "The shipment's logger cross-check (#38): matched (a reading at least every logger interval from the seal to the departure, each within the setpoint tolerance), incomplete (a gap), out_of_range (a reading outside), missing (no signed series); the page states it instead of the mockup's claim."
              },
              "export_filed": {
                "type": "boolean",
                "description": "The national-portal filing went through (#38): the outbound rows of the lot's accepted envelopes exist and are all delivered; false: the page says it is not confirmed."
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          }
        ]
      },
      "PublicLot": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "status",
          "status_since",
          "status_reason",
          "public_id",
          "code",
          "crop",
          "variety",
          "origin_country",
          "fruit_count",
          "net_mass_kg",
          "carton_count",
          "packed_on",
          "harvested_on",
          "facility",
          "growing_area",
          "export",
          "trust",
          "verification",
          "journey",
          "ripeness",
          "lab",
          "downloads",
          "issuer"
        ],
        "properties": {
          "status": {
            "$ref": "#/components/schemas/PublicStatus"
          },
          "status_since": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicIsoDateTime"
              },
              {
                "type": "null"
              }
            ]
          },
          "status_reason": {
            "description": "P5 (#41): the reason category of a recalled or withdrawn lot (RecallReason), null otherwise. Never the recall's note, depth or who recalled it.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/RecallReason"
              },
              {
                "type": "null"
              }
            ]
          },
          "public_id": {
            "$ref": "#/components/schemas/PublicCode"
          },
          "code": {
            "$ref": "#/components/schemas/PublicCode"
          },
          "crop": {
            "type": "string",
            "x-sdk-enum": [
              "durian"
            ]
          },
          "crop_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "#156: the registry's name of the lot's crop (`crop`, a code of the crop registry) in `lang`; only with `crop_profile=1`.",
            "x-not-in-sdk": true
          },
          "ripeness_scale": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "levels_1_to_4",
              null
            ],
            "description": "#156: the crop's ripeness scale; null for a crop graded on none, whose lot has no ripeness section (`ripeness` null) and no public fruit records; only with `crop_profile=1`.",
            "x-not-in-sdk": true
          },
          "variety": {
            "$ref": "#/components/schemas/PublicText"
          },
          "origin_country": {
            "$ref": "#/components/schemas/PublicText"
          },
          "fruit_count": {
            "type": "integer",
            "minimum": 0
          },
          "net_mass_kg": {
            "type": "number",
            "minimum": 0
          },
          "carton_count": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0
          },
          "packed_on": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicIsoDate"
              },
              {
                "type": "null"
              }
            ]
          },
          "harvested_on": {
            "$ref": "#/components/schemas/PublicIsoDate"
          },
          "facility": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code",
              "name",
              "locality"
            ],
            "properties": {
              "code": {
                "$ref": "#/components/schemas/PublicCode"
              },
              "name": {
                "$ref": "#/components/schemas/PublicText"
              },
              "locality": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          "growing_area": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "code",
              "locality",
              "area_ha",
              "tree_count"
            ],
            "properties": {
              "code": {
                "$ref": "#/components/schemas/PublicCode"
              },
              "locality": {
                "$ref": "#/components/schemas/PublicText"
              },
              "area_ha": {
                "type": "number",
                "minimum": 0
              },
              "tree_count": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 0
              },
              "map": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicCommuneMap"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "#293: the commune map (PublicCommuneMap); only with `map=1`, null when the area has none.",
                "x-not-in-sdk": true
              }
            }
          },
          "export": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "market",
              "border_gate",
              "exported_on"
            ],
            "properties": {
              "market": {
                "$ref": "#/components/schemas/PublicMarket"
              },
              "border_gate": {
                "$ref": "#/components/schemas/PublicText"
              },
              "exported_on": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          "trust": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "tier",
              "tested_analytes"
            ],
            "properties": {
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "tested_analytes": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/PublicAnalyte"
                }
              },
              "limited_by": {
                "type": "array",
                "items": {
                  "type": "string",
                  "enum": [
                    "registration",
                    "harvest",
                    "measurement",
                    "override",
                    "lab",
                    "packing",
                    "shipping",
                    "inputs",
                    "sealed"
                  ]
                },
                "description": "#280: what holds the lot at `tier` before an open hold or a recall caps it; only with `trust_limits=1`. `sealed` alone: the lot was sealed at that tier when it first left the open state, and evidence added later can lower a sealed lot but never raise it. Otherwise each journey step that decides the tier, in journey order (a step at that tier, or a step the lot's stage requires that has no evidence yet), then `inputs` when the lots merged into this one decide it (a merged lot is never above the lowest of them). `override` in the measurement step's place: every measurement record of the lot had its ripeness reading overridden by a sensory assessment, and an overridden record is Self-declared whatever its device signature.",
                "x-not-in-sdk": true
              }
            }
          },
          "verification": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "signed_event_count",
              "signatures",
              "timestamp",
              "duplicate_scans",
              "seal"
            ],
            "properties": {
              "signed_event_count": {
                "type": "integer",
                "minimum": 0
              },
              "signatures": {
                "type": "string",
                "enum": [
                  "valid",
                  "invalid"
                ]
              },
              "signatures_complete": {
                "type": "boolean",
                "description": "#329: whether this answer re-verified every accepted event of the lot, so that `signed_event_count` and `signatures` are the lot's whole count and result; false while a large lot's re-verification is still in progress over requests (the count then covers the events checked so far, and the answer is `Cache-Control: private, no-store`). Only with `signatures_complete=1`.",
                "x-not-in-sdk": true
              },
              "timestamp": {
                "description": "The RFC 3161 external timestamp of the lot's seal (L11, #36): `valid` with the token's genTime only once a timestamp token was verified when stored (its message imprint is the seal's manifest hash; the TSA certificate chains to the deployment's trust store); `pending` while the sealed lot waits for one (the TSA unreachable, or its token did not verify; the backend retries); `missing` before the seal or when no TSA is configured. This backend never sends `invalid`: a token that does not verify is not stored.",
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "status",
                      "at"
                    ],
                    "properties": {
                      "status": {
                        "const": "valid"
                      },
                      "at": {
                        "$ref": "#/components/schemas/PublicIsoDateTime"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "status",
                      "at"
                    ],
                    "properties": {
                      "status": {
                        "const": "invalid"
                      },
                      "at": {
                        "oneOf": [
                          {
                            "$ref": "#/components/schemas/PublicIsoDateTime"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "status"
                    ],
                    "properties": {
                      "status": {
                        "const": "pending"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "status"
                    ],
                    "properties": {
                      "status": {
                        "const": "missing"
                      }
                    }
                  }
                ]
              },
              "duplicate_scans": {
                "type": "boolean"
              },
              "seal": {
                "description": "L10 (#35): the lot's sealed manifest (POST /v1/lots/{lot}/close), null while the lot is not signed. `signature` was verified once, by the transaction that signed it, with the key's public key (a seal that does not verify is never stored); it reads `invalid` once that key is revoked for compromise, and the public read never decodes the credential; `sealed_at` is the seal time; `manifest_sha256` the SHA-256 of the signed credential's payload.",
                "oneOf": [
                  {
                    "type": "null"
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "signature",
                      "sealed_at",
                      "manifest_sha256"
                    ],
                    "properties": {
                      "signature": {
                        "type": "string",
                        "enum": [
                          "valid",
                          "invalid"
                        ]
                      },
                      "sealed_at": {
                        "$ref": "#/components/schemas/PublicIsoDateTime"
                      },
                      "manifest_sha256": {
                        "type": "string",
                        "pattern": "^[0-9a-f]{64}$"
                      }
                    }
                  }
                ]
              }
            }
          },
          "journey": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PublicLotJourneyStep"
            },
            "maxItems": 32
          },
          "ripeness": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "exported_count",
              "device_model",
              "counts",
              "majority_level",
              "eating_window",
              "storage_temperature_c",
              "mean_confidence",
              "calibrated_on",
              "override_count"
            ],
            "properties": {
              "exported_count": {
                "type": "integer",
                "minimum": 0
              },
              "device_model": {
                "$ref": "#/components/schemas/PublicText"
              },
              "counts": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "1",
                  "2",
                  "3",
                  "4"
                ],
                "properties": {
                  "1": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "2": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "3": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "4": {
                    "type": "integer",
                    "minimum": 0
                  }
                }
              },
              "majority_level": {
                "type": "integer",
                "enum": [
                  1,
                  2,
                  3,
                  4
                ]
              },
              "eating_window": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "start",
                  "end"
                ],
                "properties": {
                  "start": {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  "end": {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  }
                }
              },
              "storage_temperature_c": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "mean_confidence": {
                "type": "number",
                "minimum": 0,
                "maximum": 1
              },
              "calibrated_on": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "override_count": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "lab": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "report_number",
              "signed_at",
              "results",
              "report_url",
              "key_custody",
              "market_approval"
            ],
            "properties": {
              "report_number": {
                "$ref": "#/components/schemas/PublicCode"
              },
              "signed_at": {
                "$ref": "#/components/schemas/PublicIsoDateTime"
              },
              "results": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/PublicLabResult"
                },
                "minItems": 1,
                "maxItems": 32
              },
              "report_url": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicSameOriginPath"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "key_custody": {
                "enum": [
                  "lab",
                  "server"
                ],
                "description": "Who holds the key that signed the report (#73): `lab`, the lab itself; `server`, the platform, which signed a lab portal entry on the lab's behalf (the lab step then stops at Cross-checked, ADR 0001)."
              },
              "market_approval": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicLabMarketApproval"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "#154: whether the lab was on the approved list of the report's market for every tested analyte on the report's signed date. Null for a market without localised names."
              }
            }
          },
          "downloads": {
            "$ref": "#/components/schemas/PublicLotDownloads"
          },
          "issuer": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicIssuer"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "PublicPeak": {
        "type": "array",
        "prefixItems": [
          {
            "type": "number",
            "minimum": -1,
            "maximum": 1
          },
          {
            "type": "number",
            "minimum": -1,
            "maximum": 1
          }
        ],
        "items": false,
        "minItems": 2,
        "maxItems": 2
      },
      "PublicFruitJourneyStep": {
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "harvest"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "facility",
              "device_model",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "measurement"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "facility": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "code",
                  "name"
                ],
                "properties": {
                  "code": {
                    "$ref": "#/components/schemas/PublicCode"
                  },
                  "name": {
                    "$ref": "#/components/schemas/PublicText"
                  }
                }
              },
              "device_model": {
                "$ref": "#/components/schemas/PublicText"
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "results",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "lab"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "results": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/PublicLabResult"
                },
                "minItems": 1,
                "maxItems": 32
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "carton_no",
              "carton_count",
              "fruit_count",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "packing"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "carton_no": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 0
              },
              "carton_count": {
                "type": "integer",
                "minimum": 0
              },
              "fruit_count": {
                "type": "integer",
                "minimum": 0
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "kind",
              "period",
              "tier",
              "source",
              "border_gate",
              "setpoint_c",
              "logger_interval_minutes",
              "logger_check",
              "export_filed",
              "device_approval"
            ],
            "properties": {
              "kind": {
                "const": "shipping"
              },
              "period": {
                "$ref": "#/components/schemas/PublicPeriod"
              },
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "source": {
                "$ref": "#/components/schemas/PublicEvidenceSource"
              },
              "border_gate": {
                "$ref": "#/components/schemas/PublicText"
              },
              "setpoint_c": {
                "type": "number"
              },
              "logger_interval_minutes": {
                "type": "integer",
                "minimum": 0
              },
              "logger_check": {
                "type": "string",
                "enum": [
                  "matched",
                  "incomplete",
                  "out_of_range",
                  "missing"
                ],
                "description": "The shipment's logger cross-check (#38): matched (a reading at least every logger interval from the seal to the departure, each within the setpoint tolerance), incomplete (a gap), out_of_range (a reading outside), missing (no signed series); the page states it instead of the mockup's claim."
              },
              "export_filed": {
                "type": "boolean",
                "description": "The national-portal filing went through (#38): the outbound rows of the lot's accepted envelopes exist and are all delivered; false: the page says it is not confirmed."
              },
              "device_approval": {
                "description": "#201: the platform approval of the devices this step's evidence comes from; null for a step no device signs.",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicDeviceApproval"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          }
        ]
      },
      "PublicFruit": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "status",
          "status_since",
          "status_reason",
          "public_id",
          "code",
          "crop",
          "variety",
          "harvested_on",
          "harvest_place",
          "carton_no",
          "lot",
          "trust",
          "scan",
          "measurement",
          "origin",
          "journey",
          "downloads",
          "report"
        ],
        "properties": {
          "status": {
            "$ref": "#/components/schemas/PublicStatus"
          },
          "status_since": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicIsoDateTime"
              },
              {
                "type": "null"
              }
            ]
          },
          "status_reason": {
            "description": "P5 (#41): the reason category of a recalled or withdrawn lot (RecallReason), null otherwise. Never the recall's note, depth or who recalled it.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/RecallReason"
              },
              {
                "type": "null"
              }
            ]
          },
          "public_id": {
            "$ref": "#/components/schemas/PublicCode"
          },
          "code": {
            "$ref": "#/components/schemas/PublicCode"
          },
          "crop": {
            "type": "string",
            "enum": [
              "durian"
            ]
          },
          "variety": {
            "$ref": "#/components/schemas/PublicText"
          },
          "harvested_on": {
            "$ref": "#/components/schemas/PublicIsoDate"
          },
          "harvest_place": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicText"
              },
              {
                "type": "null"
              }
            ]
          },
          "carton_no": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0
          },
          "lot": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "public_id",
              "code"
            ],
            "properties": {
              "public_id": {
                "$ref": "#/components/schemas/PublicCode"
              },
              "code": {
                "$ref": "#/components/schemas/PublicCode"
              }
            }
          },
          "trust": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "tier",
              "signature"
            ],
            "properties": {
              "tier": {
                "$ref": "#/components/schemas/PublicTrustTier"
              },
              "signature": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "status",
                  "value"
                ],
                "properties": {
                  "status": {
                    "type": "string",
                    "enum": [
                      "valid",
                      "invalid"
                    ]
                  },
                  "value": {
                    "type": "string",
                    "pattern": "^[0-9a-f]{16,1024}$"
                  }
                }
              },
              "limited_by": {
                "type": "array",
                "items": {
                  "type": "string",
                  "enum": [
                    "registration",
                    "harvest",
                    "measurement",
                    "override",
                    "lab",
                    "packing",
                    "shipping",
                    "inputs",
                    "sealed"
                  ]
                },
                "description": "#280: what holds the fruit at `tier` before an open hold or a recall caps it; only with `trust_limits=1`. When the lot's tier decides the fruit's: what holds the lot (the lot record's `trust.limited_by`, its registration step included); `measurement` when the fruit's own measurement record decides it. Steps in journey order (`override` in the measurement step's place, as the lot's), then `inputs`, then `sealed`. `override` alone: the fruit's own ripeness reading was overridden by a sensory assessment, and an overridden record is Self-declared whatever its device signature, its lot or its seal.",
                "x-not-in-sdk": true
              }
            }
          },
          "scan": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "scan_number",
              "scanned_on",
              "city",
              "region",
              "days_since_harvest"
            ],
            "properties": {
              "scan_number": {
                "type": "integer",
                "minimum": 1
              },
              "scanned_on": {
                "$ref": "#/components/schemas/PublicIsoDate"
              },
              "city": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "region": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "days_since_harvest": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 0
              }
            }
          },
          "measurement": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "measured_at",
              "device",
              "ripeness_level",
              "model_confidence",
              "weight_kg",
              "grade",
              "eating_window",
              "waveform_peaks"
            ],
            "properties": {
              "measured_at": {
                "$ref": "#/components/schemas/PublicIsoDateTime"
              },
              "device": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "model",
                  "serial"
                ],
                "properties": {
                  "model": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "serial": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  }
                }
              },
              "ripeness_level": {
                "type": "integer",
                "enum": [
                  1,
                  2,
                  3,
                  4
                ]
              },
              "model_confidence": {
                "type": "number",
                "minimum": 0,
                "maximum": 1
              },
              "weight_kg": {
                "type": "number",
                "exclusiveMinimum": 0
              },
              "grade": {
                "type": "string",
                "enum": [
                  "A",
                  "B",
                  "reject"
                ]
              },
              "eating_window": {
                "type": [
                  "object",
                  "null"
                ],
                "additionalProperties": false,
                "required": [
                  "start",
                  "end"
                ],
                "properties": {
                  "start": {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  "end": {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  }
                }
              },
              "waveform_peaks": {
                "type": [
                  "array",
                  "null"
                ],
                "items": {
                  "$ref": "#/components/schemas/PublicPeak"
                },
                "maxItems": 4096
              }
            }
          },
          "origin": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "growing_area",
              "grower",
              "orchard_position",
              "tree_age_years",
              "last_spray",
              "certification",
              "satellite"
            ],
            "properties": {
              "growing_area": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "code",
                  "area_ha",
                  "tree_count"
                ],
                "properties": {
                  "code": {
                    "$ref": "#/components/schemas/PublicCode"
                  },
                  "area_ha": {
                    "type": "number",
                    "minimum": 0
                  },
                  "tree_count": {
                    "type": [
                      "integer",
                      "null"
                    ],
                    "minimum": 0
                  }
                }
              },
              "grower": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "name",
                  "organization"
                ],
                "properties": {
                  "name": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "organization": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/PublicText"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  }
                }
              },
              "orchard_position": {
                "type": [
                  "object",
                  "null"
                ],
                "additionalProperties": false,
                "required": [
                  "block",
                  "row"
                ],
                "properties": {
                  "block": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 16
                  },
                  "row": {
                    "type": "integer",
                    "minimum": 1
                  }
                }
              },
              "tree_age_years": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 0
              },
              "last_spray": {
                "type": [
                  "object",
                  "null"
                ],
                "additionalProperties": false,
                "required": [
                  "applied_on",
                  "withholding_days"
                ],
                "properties": {
                  "applied_on": {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  "withholding_days": {
                    "type": "integer",
                    "minimum": 0
                  }
                }
              },
              "certification": {
                "type": [
                  "object",
                  "null"
                ],
                "additionalProperties": false,
                "required": [
                  "scheme",
                  "status"
                ],
                "properties": {
                  "scheme": {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "valid",
                      "expired",
                      "suspended"
                    ]
                  }
                }
              },
              "satellite": {
                "type": [
                  "object",
                  "null"
                ],
                "additionalProperties": false,
                "required": [
                  "source",
                  "image_date",
                  "area_matches_registration",
                  "deforestation_detected",
                  "image_url"
                ],
                "properties": {
                  "source": {
                    "$ref": "#/components/schemas/PublicText"
                  },
                  "image_date": {
                    "$ref": "#/components/schemas/PublicIsoDate"
                  },
                  "area_matches_registration": {
                    "type": "boolean"
                  },
                  "deforestation_detected": {
                    "type": "boolean"
                  },
                  "image_url": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/PublicSameOriginPath"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  }
                }
              },
              "map": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicCommuneMap"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "#293: the commune map (PublicCommuneMap); only with `map=1`, null when the area has none.",
                "x-not-in-sdk": true
              }
            }
          },
          "journey": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PublicFruitJourneyStep"
            },
            "maxItems": 32
          },
          "downloads": {
            "$ref": "#/components/schemas/PublicDownloads"
          },
          "report": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "scan_threshold",
              "url"
            ],
            "properties": {
              "scan_threshold": {
                "type": "integer",
                "minimum": 1
              },
              "url": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/PublicSameOriginPath"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          }
        }
      },
      "EnvelopeSummary": {
        "type": "object",
        "description": "One stored envelope of the device message log (#117): routing and outcome columns only.",
        "required": [
          "id",
          "device_id",
          "site",
          "facility",
          "seq",
          "kind",
          "event_type",
          "event_time",
          "received_at",
          "status",
          "reasons",
          "lot"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string",
            "description": "Envelope id."
          },
          "device_id": {
            "type": "string"
          },
          "site": {
            "type": "string",
            "description": "Site of the ingest route."
          },
          "facility": {
            "type": [
              "string",
              "null"
            ],
            "description": "The envelope context's facility, null when it names none."
          },
          "seq": {
            "type": "integer",
            "description": "The device's sequence number."
          },
          "kind": {
            "type": "string",
            "enum": [
              "telemetry",
              "event",
              "status"
            ]
          },
          "event_type": {
            "type": [
              "string",
              "null"
            ],
            "description": "Event type; null for telemetry and status."
          },
          "event_time": {
            "type": "string",
            "description": "The device's time, as sent."
          },
          "received_at": {
            "type": "number",
            "description": "Server receive time, epoch seconds."
          },
          "status": {
            "type": "string",
            "enum": [
              "accepted",
              "quarantined",
              "rejected_after_review"
            ]
          },
          "reasons": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Why ingest quarantined it; empty when accepted on arrival."
          },
          "lot": {
            "type": [
              "string",
              "null"
            ],
            "description": "The envelope context's lot."
          }
        }
      },
      "EnvelopePage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/EnvelopeSummary"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page. A page with fewer items than the limit, or none, may still have one."
          }
        }
      },
      "EnvelopeDetail": {
        "type": "object",
        "description": "One stored envelope with its signed payload as stored and its signature checked again.",
        "required": [
          "id",
          "device_id",
          "site",
          "facility",
          "seq",
          "kind",
          "event_type",
          "event_time",
          "received_at",
          "status",
          "reasons",
          "lot",
          "growing_area",
          "payload",
          "signature"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string",
            "description": "Envelope id."
          },
          "device_id": {
            "type": "string"
          },
          "site": {
            "type": "string",
            "description": "Site of the ingest route."
          },
          "facility": {
            "type": [
              "string",
              "null"
            ],
            "description": "The envelope context's facility, null when it names none."
          },
          "seq": {
            "type": "integer",
            "description": "The device's sequence number."
          },
          "kind": {
            "type": "string",
            "enum": [
              "telemetry",
              "event",
              "status"
            ]
          },
          "event_type": {
            "type": [
              "string",
              "null"
            ],
            "description": "Event type; null for telemetry and status."
          },
          "event_time": {
            "type": "string",
            "description": "The device's time, as sent."
          },
          "received_at": {
            "type": "number",
            "description": "Server receive time, epoch seconds."
          },
          "status": {
            "type": "string",
            "enum": [
              "accepted",
              "quarantined",
              "rejected_after_review"
            ]
          },
          "reasons": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Why ingest quarantined it; empty when accepted on arrival."
          },
          "lot": {
            "type": [
              "string",
              "null"
            ],
            "description": "The envelope context's lot."
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ],
            "description": "The envelope context's growing area."
          },
          "payload": {
            "type": "object",
            "description": "The signed envelope exactly as stored (spec envelope v1)."
          },
          "signature": {
            "type": "object",
            "required": [
              "status",
              "kid",
              "key_status"
            ],
            "additionalProperties": false,
            "description": "`valid`: the stored key named by `sig.kid` verifies the stored payload; `invalid`: it does not (the payload or the key changed since ingest); `unknown_key`: no stored key has that kid; `unsigned`: the payload has no `sig`. The key itself is never returned.",
            "properties": {
              "status": {
                "type": "string",
                "enum": [
                  "valid",
                  "invalid",
                  "unknown_key",
                  "unsigned"
                ]
              },
              "kid": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "key_status": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "`active` or `revoked`; null without a key."
              }
            }
          }
        }
      },
      "Carton": {
        "type": "object",
        "required": [
          "tenant",
          "code",
          "lot",
          "carton_no",
          "public_id",
          "qr_url",
          "net_mass_kg",
          "fruit_count",
          "fruit_mass_kg",
          "labels_printed_at",
          "created_by",
          "created_at",
          "updated_at"
        ],
        "additionalProperties": false,
        "description": "A carton of one lot (issue #37); its contents are fruits of that lot.",
        "properties": {
          "tenant": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "pattern": "^C-[0-9]{3,19}-[0-9]{4}$",
            "description": "`C-<lot seq>-<carton number>`."
          },
          "lot": {
            "type": "string",
            "description": "Code of the carton's lot."
          },
          "carton_no": {
            "type": "integer",
            "minimum": 1,
            "maximum": 9999,
            "description": "Number within the lot."
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "128 random bits as hex."
          },
          "qr_url": {
            "type": "string",
            "description": "What the carton label's QR code carries (ADR 0004): a GS1 Digital Link `<resolver>/01/<gtin>/10/<lot>/21/<serial>` when the lot has a GTIN and a lot code of at most 20 characters (GS1 AI 10), else `<resolver>/q/<public_id>`."
          },
          "net_mass_kg": {
            "type": [
              "number",
              "null"
            ],
            "description": "Weighed net mass; null until the contents are set."
          },
          "fruit_count": {
            "type": "integer",
            "minimum": 0
          },
          "fruit_mass_kg": {
            "type": "number",
            "description": "Sum of the measured (scale) weights of its fruits, 3 decimals."
          },
          "labels_printed_at": {
            "type": "number",
            "description": "Unix seconds: the carton label's print time (creation)."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          }
        },
        "example": {
          "tenant": "coop-dl",
          "code": "C-014-0017",
          "lot": "LO-260928-014",
          "carton_no": 17,
          "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
          "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
          "net_mass_kg": 8.53,
          "fruit_count": 3,
          "fruit_mass_kg": 8.89,
          "labels_printed_at": 1790000300.5,
          "created_by": "packer@coop.example",
          "created_at": 1790000300.5,
          "updated_at": 1790000310.0
        }
      },
      "CartonDetail": {
        "type": "object",
        "required": [
          "tenant",
          "code",
          "lot",
          "carton_no",
          "public_id",
          "qr_url",
          "net_mass_kg",
          "fruit_count",
          "fruit_mass_kg",
          "labels_printed_at",
          "created_by",
          "created_at",
          "updated_at",
          "fruits"
        ],
        "additionalProperties": false,
        "description": "A carton with the codes of its fruits (by fruit number).",
        "properties": {
          "tenant": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "pattern": "^C-[0-9]{3,19}-[0-9]{4}$",
            "description": "`C-<lot seq>-<carton number>`."
          },
          "lot": {
            "type": "string",
            "description": "Code of the carton's lot."
          },
          "carton_no": {
            "type": "integer",
            "minimum": 1,
            "maximum": 9999,
            "description": "Number within the lot."
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "128 random bits as hex."
          },
          "qr_url": {
            "type": "string",
            "description": "What the carton label's QR code carries (ADR 0004): a GS1 Digital Link `<resolver>/01/<gtin>/10/<lot>/21/<serial>` when the lot has a GTIN and a lot code of at most 20 characters (GS1 AI 10), else `<resolver>/q/<public_id>`."
          },
          "net_mass_kg": {
            "type": [
              "number",
              "null"
            ],
            "description": "Weighed net mass; null until the contents are set."
          },
          "fruit_count": {
            "type": "integer",
            "minimum": 0
          },
          "fruit_mass_kg": {
            "type": "number",
            "description": "Sum of the measured (scale) weights of its fruits, 3 decimals."
          },
          "labels_printed_at": {
            "type": "number",
            "description": "Unix seconds: the carton label's print time (creation)."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "fruits": {
            "type": "array",
            "maxItems": 32,
            "items": {
              "type": "string",
              "pattern": "^Q-[0-9]{3,19}-[0-9]{4,19}$"
            }
          }
        },
        "example": {
          "tenant": "coop-dl",
          "code": "C-014-0017",
          "lot": "LO-260928-014",
          "carton_no": 17,
          "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
          "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
          "net_mass_kg": 8.53,
          "fruit_count": 3,
          "fruit_mass_kg": 8.89,
          "labels_printed_at": 1790000300.5,
          "created_by": "packer@coop.example",
          "created_at": 1790000300.5,
          "updated_at": 1790000310.0,
          "fruits": [
            "Q-014-0049",
            "Q-014-0050",
            "Q-014-0052"
          ]
        }
      },
      "CartonPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Carton"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "CartonCreate": {
        "type": "object",
        "additionalProperties": false,
        "maxProperties": 0,
        "description": "No fields: the number, code and ids are the server's; the contents come with PUT .../fruits."
      },
      "CartonContents": {
        "type": "object",
        "required": [
          "fruits",
          "net_mass_kg"
        ],
        "additionalProperties": false,
        "description": "What the carton holds, replacing its previous contents.",
        "properties": {
          "fruits": {
            "type": "array",
            "minItems": 1,
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^Q-[0-9]{3,19}-[0-9]{4,19}$"
            },
            "description": "Codes of packable fruits of the carton's lot (status recorded or overridden, grade A or B), each in no other carton."
          },
          "net_mass_kg": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1000,
            "description": "The carton's weighed net mass."
          }
        },
        "example": {
          "fruits": [
            "Q-014-0049",
            "Q-014-0050",
            "Q-014-0052"
          ],
          "net_mass_kg": 8.53
        }
      },
      "SealRequest": {
        "type": "object",
        "required": [
          "seal_no"
        ],
        "additionalProperties": false,
        "properties": {
          "seal_no": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"
          }
        },
        "example": {
          "seal_no": "0492117"
        }
      },
      "AreaMassBalance": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "growing_area",
          "season",
          "harvested_kg",
          "declared_kg",
          "shipped_kg",
          "packed_lots",
          "violation"
        ],
        "description": "Harvested against shipped kg of a growing area in a season, across all tenants (aggregates only).",
        "properties": {
          "growing_area": {
            "type": "string"
          },
          "season": {
            "type": "string"
          },
          "harvested_kg": {
            "type": "number",
            "description": "Accepted harvest and receive envelopes (as the volume) plus the self-declared harvest declarations of the season."
          },
          "declared_kg": {
            "type": "number",
            "minimum": 0,
            "description": "Of which tenant-entered harvest declarations (source self_declared)."
          },
          "shipped_kg": {
            "type": "number",
            "description": "Packed net mass of the area's packed lots of the season."
          },
          "packed_lots": {
            "type": "integer",
            "minimum": 0
          },
          "violation": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "harvest_not_declared",
              "shipped_exceeds_harvest",
              null
            ],
            "description": "harvest_not_declared: nothing declared; shipped_exceeds_harvest: more packed than harvested; null when the balance holds."
          }
        },
        "example": {
          "growing_area": "VN-TGOR-0387",
          "season": "2026",
          "harvested_kg": 1820.0,
          "declared_kg": 1820.0,
          "shipped_kg": 1230.0,
          "packed_lots": 4,
          "violation": null
        }
      },
      "HarvestDeclarationCreate": {
        "type": "object",
        "required": [
          "harvest_date",
          "kg"
        ],
        "additionalProperties": false,
        "properties": {
          "harvest_date": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The harvest date; not later than today."
          },
          "kg": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1000000,
            "description": "Mass harvested on that date."
          }
        }
      },
      "HarvestDeclaration": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "growing_area",
          "harvest_date",
          "season",
          "kg",
          "source",
          "declared_by",
          "declared_at"
        ],
        "description": "A tenant-entered harvest of a growing area on one date (Self-declared).",
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "growing_area": {
            "type": "string"
          },
          "harvest_date": {
            "type": "string",
            "format": "date"
          },
          "season": {
            "type": "string",
            "description": "The ingest policy's season of the harvest date."
          },
          "kg": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "source": {
            "type": "string",
            "enum": [
              "self_declared"
            ]
          },
          "declared_by": {
            "type": "string",
            "description": "The user who declared it."
          },
          "declared_at": {
            "type": "number",
            "description": "Unix time of the declaration."
          }
        },
        "example": {
          "id": 7,
          "growing_area": "VN-TGOR-0387",
          "harvest_date": "2026-09-27",
          "season": "2026",
          "kg": 1820.0,
          "source": "self_declared",
          "declared_by": "admin@coop-dl",
          "declared_at": 1790500000.0
        }
      },
      "HarvestDeclarationPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/HarvestDeclaration"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "LotCartonBalance": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "exportable_fruits",
          "exportable_kg",
          "uncartoned_fruits",
          "uncartoned_kg",
          "violation"
        ],
        "description": "The lot's exportable fruits (L6's export) against those left out of every carton. Stated, not blocking: a lot packs with the gap and keeps it in its packing view.",
        "properties": {
          "exportable_fruits": {
            "type": "integer",
            "minimum": 0,
            "description": "Fruits recorded or overridden with grade A or B."
          },
          "exportable_kg": {
            "type": "number",
            "description": "Their measured weights (unweighed fruits add none)."
          },
          "uncartoned_fruits": {
            "type": "integer",
            "minimum": 0,
            "description": "Exportable fruits in no carton."
          },
          "uncartoned_kg": {
            "type": "number",
            "description": "Their measured weights."
          },
          "violation": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "fruit_not_cartoned",
              null
            ],
            "description": "fruit_not_cartoned: an exportable fruit is in no carton; null when every exportable fruit is cartoned."
          }
        },
        "example": {
          "exportable_fruits": 123,
          "exportable_kg": 364.2,
          "uncartoned_fruits": 0,
          "uncartoned_kg": 0.0,
          "violation": null
        }
      },
      "LotPacking": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "status",
          "packed_at",
          "cartons",
          "fruits",
          "net_mass_kg",
          "fruit_mass_kg",
          "seal_numbers",
          "mass_balance"
        ],
        "description": "A lot's packing (issue #37): totals, seal numbers (newest first, at most 50) and the mass balance with every violation counted (at most 50 listed, in carton order).",
        "properties": {
          "lot": {
            "type": "string"
          },
          "status": {
            "enum": [
              "draft",
              "open",
              "paused",
              "closed",
              "packed",
              "shipped",
              "recalled",
              "withdrawn"
            ]
          },
          "packed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the pack event (the first seal)."
          },
          "cartons": {
            "type": "integer",
            "minimum": 0
          },
          "fruits": {
            "type": "integer",
            "minimum": 0
          },
          "net_mass_kg": {
            "type": "number",
            "description": "Sum of the cartons' net masses."
          },
          "fruit_mass_kg": {
            "type": "number",
            "description": "Sum of the packed fruits' measured weights."
          },
          "seal_numbers": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "type": "object",
              "required": [
                "seal_no",
                "sealed_by",
                "sealed_at"
              ],
              "additionalProperties": false,
              "properties": {
                "seal_no": {
                  "type": "string"
                },
                "sealed_by": {
                  "type": "string"
                },
                "sealed_at": {
                  "type": "number"
                }
              }
            }
          },
          "mass_balance": {
            "type": "object",
            "required": [
              "tolerance",
              "violation_count",
              "violations",
              "lot",
              "area"
            ],
            "additionalProperties": false,
            "properties": {
              "tolerance": {
                "type": "number",
                "description": "Allowed difference between a carton's net mass and its fruits' measured weights, as a fraction of the latter."
              },
              "violation_count": {
                "type": "integer",
                "minimum": 0,
                "description": "Violating cartons plus the lot's own violation (`lot.violation`), all counted."
              },
              "violations": {
                "type": "array",
                "maxItems": 50,
                "items": {
                  "type": "object",
                  "required": [
                    "carton",
                    "kinds"
                  ],
                  "additionalProperties": false,
                  "properties": {
                    "carton": {
                      "type": "string"
                    },
                    "kinds": {
                      "type": "array",
                      "minItems": 1,
                      "items": {
                        "enum": [
                          "carton_empty",
                          "carton_unweighed",
                          "fruit_not_packable",
                          "fruit_unweighed",
                          "carton_mass_mismatch"
                        ]
                      }
                    }
                  }
                }
              },
              "lot": {
                "$ref": "#/components/schemas/LotCartonBalance"
              },
              "area": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/AreaMassBalance"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "The lot's growing area for its season; null without a growing area."
              }
            }
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "status": "packed",
          "packed_at": 1790003600.0,
          "cartons": 41,
          "fruits": 123,
          "net_mass_kg": 349.6,
          "fruit_mass_kg": 364.2,
          "seal_numbers": [
            {
              "seal_no": "0492117",
              "sealed_by": "packer@coop.example",
              "sealed_at": 1790003600.0
            }
          ],
          "mass_balance": {
            "tolerance": 0.05,
            "violation_count": 0,
            "violations": [],
            "lot": {
              "exportable_fruits": 123,
              "exportable_kg": 364.2,
              "uncartoned_fruits": 0,
              "uncartoned_kg": 0.0,
              "violation": null
            },
            "area": {
              "growing_area": "VN-TGOR-0387",
              "season": "2026",
              "harvested_kg": 1820.0,
              "declared_kg": 1820.0,
              "shipped_kg": 1230.0,
              "packed_lots": 4,
              "violation": null
            }
          }
        }
      },
      "ShipmentCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "facility",
          "container",
          "border_gate",
          "destination",
          "setpoint_c",
          "logger"
        ],
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$",
            "description": "Unique within the tenant (a lot code's pattern)."
          },
          "facility": {
            "type": "string",
            "description": "The departure facility: one of the tenant's, within the caller's facilities."
          },
          "container": {
            "type": "string",
            "pattern": "^[A-Z]{3}[UJZ][0-9]{7}$",
            "description": "ISO 6346 container number; its check digit must be valid."
          },
          "border_gate": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100,
            "description": "The border gate the shipment heads for (a display string)."
          },
          "destination": {
            "type": "string",
            "enum": [
              "CN"
            ],
            "description": "Destination market, ISO 3166-1 alpha-2."
          },
          "setpoint_c": {
            "type": "number",
            "minimum": -30,
            "maximum": 30,
            "description": "Reefer setpoint, Cel."
          },
          "tolerance_c": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 5,
            "default": 2.0,
            "description": "Deviation from the setpoint a logger reading may show, Cel."
          },
          "logger_interval_minutes": {
            "type": "integer",
            "minimum": 1,
            "maximum": 15,
            "default": 15,
            "description": "The longest interval the logger may leave between readings."
          },
          "logger": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "device_id"
            ],
            "description": "The independent temperature logger: an active device of the tenant's registry at the departure facility whose profile declares air.temperature (vn.agritrace.reefer-logger). The device and its keys are registered by a device admin; the shipment stores no key.",
            "properties": {
              "device_id": {
                "type": "string",
                "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
              }
            }
          }
        }
      },
      "ShipmentLotLink": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$",
            "description": "A packed lot of the shipment's facility."
          }
        }
      },
      "ShipmentDepart": {
        "type": "object",
        "additionalProperties": false,
        "maxProperties": 0,
        "description": "An empty object."
      },
      "LoggerSeries": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "logger",
          "shipment",
          "capability",
          "unit",
          "readings",
          "sig"
        ],
        "description": "A temperature series of the shipment's logger, signed ES256 over the canonical JSON (sorted keys, no whitespace, UTF-8) of every member but `sig`, as a device envelope, with an active key of the device registry owned by the shipment's active logger (`sig.kid` names it).",
        "properties": {
          "logger": {
            "type": "string",
            "description": "The shipment's logger device id."
          },
          "shipment": {
            "type": "string",
            "description": "The shipment code."
          },
          "capability": {
            "const": "air.temperature"
          },
          "unit": {
            "const": "Cel"
          },
          "readings": {
            "type": "array",
            "minItems": 1,
            "maxItems": 2880,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "time",
                "value"
              ],
              "properties": {
                "time": {
                  "type": "string",
                  "format": "date-time",
                  "description": "ISO 8601 instant with an offset; distinct within the document."
                },
                "value": {
                  "type": "number",
                  "minimum": -40,
                  "maximum": 85
                }
              }
            }
          },
          "sig": {
            "type": "object",
            "required": [
              "alg",
              "kid",
              "value"
            ],
            "properties": {
              "alg": {
                "const": "ES256"
              },
              "kid": {
                "type": "string",
                "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
              },
              "value": {
                "type": "string",
                "description": "base64url(r || s)."
              }
            }
          }
        }
      },
      "LoggerCheck": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "status",
          "readings",
          "considered",
          "first_at",
          "last_at",
          "min_c",
          "max_c",
          "seal_at",
          "until",
          "gap_count",
          "gaps",
          "out_of_range_count",
          "out_of_range",
          "complete",
          "within_setpoint"
        ],
        "description": "The logger cross-check, recomputed by every link, upload and departure: from the seal time (the earliest seal time of the shipment's lots) every reading within setpoint +/- tolerance and no gap above the logger interval up to the departure. Times are Unix seconds. At most 20 gaps and 20 out-of-range readings are listed; all are counted.",
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "missing",
              "incomplete",
              "out_of_range",
              "matched"
            ]
          },
          "readings": {
            "type": "integer",
            "minimum": 0
          },
          "considered": {
            "type": "integer",
            "minimum": 0,
            "description": "Readings from the seal time on."
          },
          "first_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "last_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "min_c": {
            "type": [
              "number",
              "null"
            ]
          },
          "max_c": {
            "type": [
              "number",
              "null"
            ]
          },
          "seal_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "until": {
            "type": [
              "number",
              "null"
            ],
            "description": "The departure; null while the shipment is open."
          },
          "gap_count": {
            "type": "integer",
            "minimum": 0
          },
          "gaps": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "kind",
                "from",
                "to",
                "minutes"
              ],
              "properties": {
                "kind": {
                  "type": "string",
                  "enum": [
                    "after_seal",
                    "between_readings",
                    "before_departure"
                  ]
                },
                "from": {
                  "type": "number"
                },
                "to": {
                  "type": "number"
                },
                "minutes": {
                  "type": "number"
                }
              }
            }
          },
          "out_of_range_count": {
            "type": "integer",
            "minimum": 0
          },
          "out_of_range": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "at",
                "celsius"
              ],
              "properties": {
                "at": {
                  "type": "number"
                },
                "celsius": {
                  "type": "number"
                }
              }
            }
          },
          "complete": {
            "type": "boolean"
          },
          "within_setpoint": {
            "type": "boolean"
          }
        }
      },
      "NationalPortalFiling": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "rows",
          "delivered",
          "pending",
          "failing",
          "filed"
        ],
        "description": "The national-portal filing of the accepted envelopes of the shipment's lots (#299): the outbound rows of the national portal's own target only (a local EPCIS file archive or another EPCIS repository never counts), queue rows, delivered, pending, failing (pending after a failed attempt); `filed` when there is a row and every one is delivered. With no national portal target configured there is no row and `filed` is false.",
        "x-sdk-description": "The outbound backlog (every configured target) of the accepted envelopes of the shipment's lots: queue rows, delivered, pending, failing (pending after a failed attempt); `filed` when there is a row and every one is delivered.",
        "properties": {
          "rows": {
            "type": "integer",
            "minimum": 0
          },
          "delivered": {
            "type": "integer",
            "minimum": 0
          },
          "pending": {
            "type": "integer",
            "minimum": 0
          },
          "failing": {
            "type": "integer",
            "minimum": 0
          },
          "filed": {
            "type": "boolean"
          }
        }
      },
      "ShipmentLot": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "status",
          "cartons",
          "seal_no",
          "sealed_at",
          "current_seal_no",
          "seal_matches",
          "added_by",
          "added_at"
        ],
        "properties": {
          "lot": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "cartons": {
            "type": "integer",
            "minimum": 1
          },
          "seal_no": {
            "type": "string",
            "description": "The lot's seal number when it was linked."
          },
          "sealed_at": {
            "type": "number"
          },
          "current_seal_no": {
            "type": [
              "string",
              "null"
            ],
            "description": "The lot's seal number now."
          },
          "seal_matches": {
            "type": "boolean"
          },
          "added_by": {
            "type": "string"
          },
          "added_at": {
            "type": "number"
          }
        }
      },
      "Shipment": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "facility",
          "container",
          "border_gate",
          "destination",
          "setpoint_c",
          "tolerance_c",
          "logger_interval_minutes",
          "logger",
          "status",
          "created_by",
          "created_at",
          "departed_by",
          "departed_at",
          "lots",
          "logger_check",
          "national_portal",
          "consignee",
          "documents",
          "paperwork",
          "amendments"
        ],
        "properties": {
          "code": {
            "type": "string"
          },
          "facility": {
            "type": "string"
          },
          "container": {
            "type": "string"
          },
          "border_gate": {
            "type": "string"
          },
          "destination": {
            "type": "string"
          },
          "setpoint_c": {
            "type": "number"
          },
          "tolerance_c": {
            "type": "number"
          },
          "logger_interval_minutes": {
            "type": "integer",
            "minimum": 1,
            "maximum": 15
          },
          "logger": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "device_id"
            ],
            "properties": {
              "device_id": {
                "type": "string"
              }
            }
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "departed"
            ]
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "departed_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "departed_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "lots": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/ShipmentLot"
            }
          },
          "logger_check": {
            "$ref": "#/components/schemas/LoggerCheck"
          },
          "national_portal": {
            "$ref": "#/components/schemas/NationalPortalFiling"
          },
          "upload": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "id",
              "readings",
              "added"
            ],
            "description": "Only in the answer of an upload: the stored upload, its readings and how many were new.",
            "properties": {
              "id": {
                "type": "integer"
              },
              "readings": {
                "type": "integer",
                "minimum": 1
              },
              "added": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "consignee": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/Consignee"
              },
              {
                "type": "null"
              }
            ]
          },
          "documents": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/ShipmentDocument"
            }
          },
          "paperwork": {
            "$ref": "#/components/schemas/ShipmentPaperwork"
          },
          "amendments": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/ShipmentAmendment"
            }
          }
        }
      },
      "Lab": {
        "type": "object",
        "description": "An accredited lab partner (platform record, no tenant). `in_force`: status active and `valid_to` today or later (Asia/Ho_Chi_Minh); only labs in force that hold an active key are assigned samples.",
        "required": [
          "code",
          "name",
          "accreditation",
          "valid_to",
          "status",
          "created_at",
          "updated_at",
          "in_force",
          "accreditation_body",
          "accreditation_number",
          "accreditation_scope"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^LAB-[A-Z]{2}-[A-Z0-9]{1,16}$"
          },
          "name": {
            "type": "string"
          },
          "accreditation": {
            "type": "string"
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "description": "Last day the accreditation is valid."
          },
          "status": {
            "enum": [
              "active",
              "suspended"
            ]
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "in_force": {
            "type": "boolean"
          },
          "accreditation_body": {
            "type": [
              "string",
              "null"
            ],
            "description": "Accreditation body, e.g. `BoA (VILAS)` (#73); null when not recorded."
          },
          "accreditation_number": {
            "type": [
              "string",
              "null"
            ],
            "description": "Accreditation certificate number (#73); null when not recorded."
          },
          "accreditation_scope": {
            "type": [
              "string",
              "null"
            ],
            "description": "The accredited scope: the tests the accreditation covers (#73); null when not recorded."
          }
        },
        "example": {
          "code": "LAB-VN-118",
          "name": "Phòng thử nghiệm mẫu",
          "accreditation": "VILAS 118 (ISO/IEC 17025)",
          "valid_to": "2027-12-31",
          "status": "active",
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5,
          "in_force": true,
          "accreditation_body": "BoA (VILAS)",
          "accreditation_number": "VILAS 118",
          "accreditation_scope": "Cadmium (ICP-MS) and auramine O (LC-MS/MS) in fresh fruit"
        }
      },
      "LabPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Lab"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "LabCreate": {
        "type": "object",
        "required": [
          "code",
          "name",
          "accreditation",
          "valid_to"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^LAB-[A-Z]{2}-[A-Z0-9]{1,16}$"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "accreditation": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Accreditation scheme and number, e.g. `VILAS 118 (ISO/IEC 17025)`."
          },
          "valid_to": {
            "type": "string",
            "format": "date"
          },
          "accreditation_body": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200
          },
          "accreditation_number": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 64
          },
          "accreditation_scope": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 1000
          }
        },
        "example": {
          "code": "LAB-VN-118",
          "name": "Phòng thử nghiệm mẫu",
          "accreditation": "VILAS 118 (ISO/IEC 17025)",
          "valid_to": "2027-12-31"
        }
      },
      "LabUpdate": {
        "type": "object",
        "minProperties": 1,
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "accreditation": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "valid_to": {
            "type": "string",
            "format": "date"
          },
          "status": {
            "enum": [
              "active",
              "suspended"
            ]
          },
          "accreditation_body": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200,
            "description": "null clears it."
          },
          "accreditation_number": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 64,
            "description": "null clears it."
          },
          "accreditation_scope": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 1000,
            "description": "null clears it."
          }
        },
        "example": {
          "status": "suspended"
        }
      },
      "LabKey": {
        "type": "object",
        "description": "A lab's result-signing public key. The PEM is never returned; `fingerprint_sha256` is the SHA-256 of the key's SubjectPublicKeyInfo DER and `fingerprint` its short display form. `custody` (#73): `lab`, the lab holds the private key and registered the public one; `server`, the platform generated the pair and holds the private key (encrypted, never returned) to sign the results the lab's portal users enter, which therefore never count as signed by the accredited lab (ADR 0001).",
        "required": [
          "kid",
          "lab",
          "status",
          "created_at",
          "revoked_at",
          "revoke_reason",
          "revoked_by",
          "fingerprint_sha256",
          "fingerprint",
          "custody"
        ],
        "additionalProperties": false,
        "properties": {
          "kid": {
            "type": "string"
          },
          "lab": {
            "type": "string"
          },
          "status": {
            "enum": [
              "active",
              "revoked"
            ]
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "rotation",
              "compromise",
              null
            ]
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "fingerprint_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "fingerprint": {
            "type": "string"
          },
          "custody": {
            "enum": [
              "lab",
              "server"
            ]
          }
        },
        "example": {
          "kid": "LAB-VN-118.2026",
          "lab": "LAB-VN-118",
          "status": "active",
          "created_at": 1790000000.5,
          "revoked_at": null,
          "revoke_reason": null,
          "revoked_by": null,
          "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
          "fingerprint": "19fc…e0d9",
          "custody": "lab"
        }
      },
      "LabKeyPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LabKey"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "LabKeyCreate": {
        "type": "object",
        "required": [
          "kid",
          "public_key_pem"
        ],
        "additionalProperties": false,
        "properties": {
          "kid": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",
            "description": "Key id; one namespace with device and gateway keys."
          },
          "public_key_pem": {
            "type": "string",
            "maxLength": 1024,
            "description": "EC P-256 public key, PEM SubjectPublicKeyInfo."
          }
        },
        "example": {
          "kid": "LAB-VN-118.2026",
          "public_key_pem": "-----BEGIN PUBLIC KEY-----\n…\n-----END PUBLIC KEY-----\n"
        }
      },
      "SampleItem": {
        "type": "object",
        "required": [
          "k",
          "fruit",
          "status"
        ],
        "additionalProperties": false,
        "properties": {
          "k": {
            "type": "integer",
            "minimum": 1,
            "description": "Sample number within the lot's sampling."
          },
          "fruit": {
            "type": "string",
            "description": "Fruit code as printed on the label."
          },
          "status": {
            "enum": [
              "selected",
              "received",
              "passed",
              "failed"
            ]
          }
        }
      },
      "SampleAnalyte": {
        "enum": [
          "cadmium",
          "auramine_o"
        ]
      },
      "LotSampling": {
        "type": "object",
        "description": "The one sampling of a lot: the rule and the rates it was computed from, the population (the lot's export fruits), the lab the system assigned, the test scope and the fruits drawn.",
        "required": [
          "lot",
          "lab",
          "rule",
          "population",
          "sample_count",
          "analytes",
          "selected_by",
          "selected_at",
          "samples",
          "report"
        ],
        "additionalProperties": false,
        "properties": {
          "lot": {
            "type": "string"
          },
          "lab": {
            "type": "object",
            "required": [
              "code",
              "name"
            ],
            "additionalProperties": false,
            "properties": {
              "code": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "rule": {
            "type": "object",
            "required": [
              "id",
              "source",
              "base_rate",
              "risk_score",
              "rate",
              "factors"
            ],
            "additionalProperties": false,
            "properties": {
              "id": {
                "type": "string",
                "description": "`cn-durian-protocol-2022`: 2% of a consignment, 1% after two years without violations."
              },
              "source": {
                "type": "string",
                "description": "Where the rule is stated."
              },
              "base_rate": {
                "type": "number"
              },
              "risk_score": {
                "type": "number",
                "minimum": 1
              },
              "rate": {
                "type": "number"
              },
              "factors": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "clean_history",
                  "override_share",
                  "high_overrides",
                  "over_quota",
                  "low_headroom"
                ],
                "properties": {
                  "clean_history": {
                    "type": "boolean"
                  },
                  "override_share": {
                    "type": "number"
                  },
                  "high_overrides": {
                    "type": "boolean"
                  },
                  "over_quota": {
                    "type": "boolean"
                  },
                  "low_headroom": {
                    "type": "boolean"
                  }
                }
              }
            }
          },
          "population": {
            "type": "integer",
            "minimum": 1
          },
          "sample_count": {
            "type": "integer",
            "minimum": 1
          },
          "analytes": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SampleAnalyte"
            }
          },
          "selected_by": {
            "type": "string"
          },
          "selected_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "samples": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SampleItem"
            }
          },
          "report": {
            "description": "The lab's signed report (P4, #40), null until the lab submits it.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/LabReport"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "lab": {
            "code": "LAB-VN-118",
            "name": "Phòng thử nghiệm mẫu"
          },
          "rule": {
            "id": "cn-durian-protocol-2022",
            "source": "https://trungtamwto.vn/thi-truong-duc/21143-sau-rieng-viet-nam-xuat-khau-chinh-ngach-sang-trung-quoc",
            "base_rate": 0.02,
            "risk_score": 1.0,
            "rate": 0.02,
            "factors": {
              "clean_history": false,
              "override_share": 0.0234,
              "high_overrides": false,
              "over_quota": false,
              "low_headroom": false
            }
          },
          "population": 123,
          "sample_count": 3,
          "analytes": [
            "cadmium",
            "auramine_o"
          ],
          "selected_by": "operator@coop.example",
          "selected_at": 1790000000.5,
          "samples": [
            {
              "k": 1,
              "fruit": "Q-014-0017",
              "status": "selected"
            },
            {
              "k": 2,
              "fruit": "Q-014-0062",
              "status": "selected"
            },
            {
              "k": 3,
              "fruit": "Q-014-0109",
              "status": "selected"
            }
          ],
          "report": null
        }
      },
      "LotSamplingRead": {
        "type": "object",
        "required": [
          "sampling"
        ],
        "additionalProperties": false,
        "properties": {
          "sampling": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/LotSampling"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "LabAssignment": {
        "type": "object",
        "required": [
          "id",
          "exporter",
          "lot",
          "facility",
          "analytes",
          "sample_count",
          "selected_at",
          "samples",
          "report"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer"
          },
          "exporter": {
            "type": "string",
            "description": "Name of the tenant that owns the lot."
          },
          "lot": {
            "type": "object",
            "required": [
              "code",
              "product",
              "variety",
              "harvest_date"
            ],
            "additionalProperties": false,
            "properties": {
              "code": {
                "type": "string"
              },
              "product": {
                "type": "string"
              },
              "variety": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "harvest_date": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          },
          "facility": {
            "type": "object",
            "required": [
              "code",
              "name",
              "address",
              "province",
              "district"
            ],
            "additionalProperties": false,
            "properties": {
              "code": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "address": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "province": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "district": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          },
          "analytes": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SampleAnalyte"
            }
          },
          "sample_count": {
            "type": "integer",
            "minimum": 1
          },
          "selected_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "samples": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SampleItem"
            }
          },
          "report": {
            "description": "The report's number and verdict once submitted (P4, #40), else null.",
            "oneOf": [
              {
                "type": "object",
                "required": [
                  "report_no",
                  "passed"
                ],
                "additionalProperties": false,
                "properties": {
                  "report_no": {
                    "type": "string"
                  },
                  "passed": {
                    "type": "boolean"
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "example": {
          "id": 41,
          "exporter": "HTX Ngũ Hiệp",
          "lot": {
            "code": "LO-260928-014",
            "product": "durian",
            "variety": "Ri6",
            "harvest_date": "2026-09-27"
          },
          "facility": {
            "code": "VN-TGPH-021",
            "name": "Cơ sở đóng gói Tân Phú",
            "address": null,
            "province": "Tiền Giang",
            "district": "Cai Lậy"
          },
          "analytes": [
            "cadmium",
            "auramine_o"
          ],
          "sample_count": 3,
          "selected_at": 1790000000.5,
          "samples": [
            {
              "k": 1,
              "fruit": "Q-014-0017",
              "status": "selected"
            },
            {
              "k": 2,
              "fruit": "Q-014-0062",
              "status": "selected"
            },
            {
              "k": 3,
              "fruit": "Q-014-0109",
              "status": "selected"
            }
          ],
          "report": null
        }
      },
      "LabAssignmentPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LabAssignment"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "LabResultAnalyte": {
        "enum": [
          "cadmium",
          "auramine_o"
        ]
      },
      "LabReportResultSubmission": {
        "type": "object",
        "description": "One result of one drawn sample. `measured`: `value` at least the detection limit; `not_detected`: no `value`. Values and detection limits are in mg/kg, the unit of the market's limits.",
        "required": [
          "sample",
          "analyte",
          "outcome",
          "unit",
          "lod",
          "method"
        ],
        "additionalProperties": false,
        "properties": {
          "sample": {
            "type": "integer",
            "minimum": 1,
            "description": "The sample number k of the sampling."
          },
          "analyte": {
            "$ref": "#/components/schemas/LabResultAnalyte"
          },
          "outcome": {
            "enum": [
              "measured",
              "not_detected"
            ]
          },
          "value": {
            "type": "number",
            "minimum": 0
          },
          "unit": {
            "const": "mg/kg"
          },
          "lod": {
            "type": "number",
            "exclusiveMinimum": 0,
            "description": "Detection limit."
          },
          "method": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          }
        }
      },
      "LabReportSubmission": {
        "type": "object",
        "description": "A lab report signed like a device envelope: `sig.value` is ES256 (base64url r || s) over the canonical JSON (keys sorted, no whitespace, UTF-8) of every other member, made with an active key of the assigned lab. Every drawn sample and every analyte of the test scope exactly once; besides, at most one origin isotope result (`LabOriginResultSubmission`) per drawn sample, all compared with the same region (#40 follow-up).",
        "required": [
          "v",
          "lab",
          "sampling",
          "report_no",
          "signed_at",
          "report_sha256",
          "results",
          "sig"
        ],
        "additionalProperties": false,
        "properties": {
          "v": {
            "const": 1
          },
          "lab": {
            "type": "string",
            "description": "The assigned lab's code; it must be the caller's lab."
          },
          "sampling": {
            "type": "integer",
            "minimum": 1,
            "description": "The sampling id of the URL."
          },
          "report_no": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",
            "description": "The lab's report number, once per lab."
          },
          "signed_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the lab signed, with its UTC offset; not before the samples were drawn, not more than 300 s ahead of the server clock."
          },
          "report_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the report's PDF original."
          },
          "results": {
            "type": "array",
            "minItems": 1,
            "maxItems": 384,
            "items": {
              "oneOf": [
                {
                  "$ref": "#/components/schemas/LabReportResultSubmission"
                },
                {
                  "$ref": "#/components/schemas/LabOriginResultSubmission"
                }
              ]
            }
          },
          "sig": {
            "type": "object",
            "required": [
              "alg",
              "kid",
              "value"
            ],
            "additionalProperties": false,
            "properties": {
              "alg": {
                "const": "ES256"
              },
              "kid": {
                "type": "string"
              },
              "value": {
                "type": "string"
              }
            }
          }
        },
        "example": {
          "v": 1,
          "lab": "LAB-VN-118",
          "sampling": 41,
          "report_no": "KN-260929-0071",
          "signed_at": "2026-09-29T15:40:00+07:00",
          "report_sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
          "results": [
            {
              "sample": 1,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS"
            },
            {
              "sample": 1,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS"
            },
            {
              "sample": 2,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS"
            },
            {
              "sample": 2,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS"
            },
            {
              "sample": 3,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS"
            },
            {
              "sample": 3,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS"
            }
          ],
          "sig": {
            "alg": "ES256",
            "kid": "LAB-VN-118.2026",
            "value": "oXJnReuBsgt-B5Q50XZIMc1f4ZyKrNbBmGQGqNG_AlzMknHMQA6jRzDDnLYMSR2xQ4fONFxUvflGduCSkSCgTg"
          }
        }
      },
      "LabReportResult": {
        "type": "object",
        "description": "One stored result with the market limit that judged it (null when the market sets none).",
        "required": [
          "sample",
          "analyte",
          "outcome",
          "value",
          "unit",
          "lod",
          "method",
          "limit",
          "passed"
        ],
        "additionalProperties": false,
        "properties": {
          "sample": {
            "type": "integer",
            "minimum": 1
          },
          "analyte": {
            "$ref": "#/components/schemas/LabResultAnalyte"
          },
          "outcome": {
            "enum": [
              "measured",
              "not_detected"
            ]
          },
          "value": {
            "type": [
              "number",
              "null"
            ]
          },
          "unit": {
            "type": "string"
          },
          "lod": {
            "type": "number"
          },
          "method": {
            "type": "string"
          },
          "limit": {
            "oneOf": [
              {
                "type": "object",
                "required": [
                  "kind",
                  "value",
                  "unit",
                  "source"
                ],
                "additionalProperties": false,
                "properties": {
                  "kind": {
                    "enum": [
                      "max",
                      "banned"
                    ]
                  },
                  "value": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "unit": {
                    "type": "string"
                  },
                  "source": {
                    "type": "string"
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          },
          "passed": {
            "type": "boolean"
          }
        }
      },
      "LabReport": {
        "type": "object",
        "description": "The lab's signed report of a sampling: pass/fail per result (sample and analyte), per analyte and for the lot (`passed`); `origin` lists its origin isotope results apart (empty without one, #40 follow-up).",
        "required": [
          "report_no",
          "lab",
          "kid",
          "key_custody",
          "market",
          "signed_at",
          "report_sha256",
          "passed",
          "analytes",
          "results",
          "origin",
          "submitted_by",
          "received_at"
        ],
        "additionalProperties": false,
        "properties": {
          "report_no": {
            "type": "string"
          },
          "lab": {
            "type": "string"
          },
          "kid": {
            "type": "string",
            "description": "The lab key that signed it."
          },
          "key_custody": {
            "enum": [
              "lab",
              "server"
            ],
            "description": "Who holds the key that signed the report (#73): `lab`, the lab itself (an uploaded signed report); `server`, the platform, for the lab's portal users (a portal entry, never counted as signed by the accredited lab)."
          },
          "market": {
            "type": "string",
            "description": "ISO 3166-1 alpha-2 of the market whose limits judged it."
          },
          "signed_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "report_sha256": {
            "type": "string"
          },
          "passed": {
            "type": "boolean"
          },
          "analytes": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "analyte",
                "passed"
              ],
              "additionalProperties": false,
              "properties": {
                "analyte": {
                  "enum": [
                    "cadmium",
                    "auramine_o",
                    "origin_isotopes"
                  ]
                },
                "passed": {
                  "type": "boolean"
                }
              }
            }
          },
          "results": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LabReportResult"
            }
          },
          "origin": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LabOriginResult"
            }
          },
          "submitted_by": {
            "type": "string"
          },
          "received_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "report_pdf": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/AttachmentStored"
              },
              {
                "type": "null"
              }
            ],
            "description": "#73: the report's PDF original once the lab sent it (`PUT /v1/lab/samples/{id}/report-pdf`), null before. A staff-only attachment owned by the sampling's tenant: only its tenant-wide staff read the bytes with `GET /v1/attachments/{sha256}`, a facility-scoped grant does not, so `GET /v1/lots/{lot}/samples` omits this field for a facility-scoped grant. The lab's own views always carry it. The public record never names or serves it (`report_url` stays null)."
          }
        },
        "example": {
          "report_no": "KN-260929-0071",
          "lab": "LAB-VN-118",
          "kid": "LAB-VN-118.2026",
          "key_custody": "lab",
          "market": "CN",
          "signed_at": 1790671200.0,
          "report_sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
          "passed": true,
          "analytes": [
            {
              "analyte": "auramine_o",
              "passed": true
            },
            {
              "analyte": "cadmium",
              "passed": true
            }
          ],
          "results": [
            {
              "sample": 1,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "value": null,
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS",
              "limit": {
                "kind": "banned",
                "value": null,
                "unit": "mg/kg",
                "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
              },
              "passed": true
            },
            {
              "sample": 1,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS",
              "limit": {
                "kind": "max",
                "value": 0.05,
                "unit": "mg/kg",
                "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
              },
              "passed": true
            },
            {
              "sample": 2,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "value": null,
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS",
              "limit": {
                "kind": "banned",
                "value": null,
                "unit": "mg/kg",
                "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
              },
              "passed": true
            },
            {
              "sample": 2,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS",
              "limit": {
                "kind": "max",
                "value": 0.05,
                "unit": "mg/kg",
                "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
              },
              "passed": true
            },
            {
              "sample": 3,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "value": null,
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS",
              "limit": {
                "kind": "banned",
                "value": null,
                "unit": "mg/kg",
                "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)"
              },
              "passed": true
            },
            {
              "sample": 3,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS",
              "limit": {
                "kind": "max",
                "value": 0.05,
                "unit": "mg/kg",
                "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)"
              },
              "passed": true
            }
          ],
          "origin": [],
          "submitted_by": "lab@lab.example",
          "received_at": 1790671260.5,
          "report_pdf": null
        }
      },
      "PublicResolution": {
        "type": "object",
        "required": [
          "kind",
          "public_id",
          "locale_hint"
        ],
        "additionalProperties": false,
        "description": "What a scanned or typed code names (#139): open `/{locale}/l/{public_id}` for a lot and `/{locale}/q/{public_id}` for a fruit. `locale_hint` is the locale segment of a scanned record URL, else null.",
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "lot",
              "fruit"
            ]
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$"
          },
          "locale_hint": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "vi",
              "zh",
              "en",
              null
            ]
          }
        },
        "example": {
          "kind": "lot",
          "public_id": "5f0c2d6e8a9b4c1d2e3f405162738495",
          "locale_hint": "vi"
        }
      },
      "PublicLinkset": {
        "type": "object",
        "required": [
          "linkset"
        ],
        "additionalProperties": false,
        "description": "#162: an IETF link set (RFC 9264) as UNTP's Identity Resolver (UNTP 0.7.0) returns it: one context per thing the code names (the record, then a fruit's lot), each an `anchor` and its link relations, every relation a list of targets. Relation types: `dpp` (a UNTP Digital Product Passport), `dfr` (the packing facility's UNTP Digital Facility Record), `dcc` (the lab's UNTP Digital Conformity Credential), `https://gs1.org/voc/traceability` (the lot's EPCIS 2.0 document) and `https://gs1.org/voc/pip` (a public page, one per language).",
        "properties": {
          "linkset": {
            "type": "array",
            "minItems": 1,
            "maxItems": 2,
            "items": {
              "type": "object",
              "required": [
                "anchor"
              ],
              "additionalProperties": false,
              "properties": {
                "anchor": {
                  "type": "string",
                  "description": "The record's URL: `https://<domain>/l/{publicId}` or `https://<domain>/q/{publicId}`."
                },
                "dpp": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/PublicLinkTarget"
                  }
                },
                "dfr": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/PublicLinkTarget"
                  }
                },
                "dcc": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/PublicLinkTarget"
                  }
                },
                "https://gs1.org/voc/traceability": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/PublicLinkTarget"
                  }
                },
                "https://gs1.org/voc/pip": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/PublicLinkTarget"
                  }
                }
              }
            }
          }
        },
        "x-not-in-sdk": true
      },
      "PublicLinkTarget": {
        "type": "object",
        "required": [
          "href",
          "title"
        ],
        "additionalProperties": false,
        "description": "#162: a link target (RFC 9264).",
        "properties": {
          "href": {
            "type": "string",
            "description": "The target URL."
          },
          "title": {
            "type": "string",
            "description": "What the target is."
          },
          "type": {
            "type": "string",
            "description": "The target's media type."
          },
          "hreflang": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "The target's language, for a public page."
          }
        },
        "x-not-in-sdk": true
      },
      "LabOriginResultSubmission": {
        "type": "object",
        "description": "An optional origin isotope result of one drawn sample (#40 follow-up): whether the sample's stable isotope profile matches (`match`) or not (`mismatch`) the profile of `region`, the region it was compared with. A match passes; a mismatch fails the sample and the report (the lot's lab hold), like a failed contaminant.",
        "required": [
          "sample",
          "analyte",
          "outcome",
          "region",
          "method"
        ],
        "additionalProperties": false,
        "properties": {
          "sample": {
            "type": "integer",
            "minimum": 1,
            "description": "The sample number k of the sampling."
          },
          "analyte": {
            "const": "origin_isotopes"
          },
          "outcome": {
            "enum": [
              "match",
              "mismatch"
            ]
          },
          "region": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "The region the sample was compared with, e.g. `Tiền Giang`; the same for every origin result of the report."
          },
          "method": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          }
        },
        "example": {
          "sample": 1,
          "analyte": "origin_isotopes",
          "outcome": "match",
          "region": "Tiền Giang",
          "method": "IRMS (δ13C, δ15N, δ18O)"
        }
      },
      "LabOriginResult": {
        "type": "object",
        "description": "One stored origin isotope result (#40 follow-up): `passed` exactly when it matched.",
        "required": [
          "sample",
          "outcome",
          "region",
          "method",
          "passed"
        ],
        "additionalProperties": false,
        "properties": {
          "sample": {
            "type": "integer",
            "minimum": 1
          },
          "outcome": {
            "enum": [
              "match",
              "mismatch"
            ]
          },
          "region": {
            "type": "string"
          },
          "method": {
            "type": "string"
          },
          "passed": {
            "type": "boolean"
          }
        }
      },
      "TrustTier": {
        "type": "string",
        "enum": [
          "self_declared",
          "device_recorded",
          "cross_checked",
          "lab_verified"
        ],
        "description": "Trust tiers, lowest first."
      },
      "TrustReason": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "params"
        ],
        "properties": {
          "code": {
            "type": "string",
            "description": "A stable reason code of the trust engine (trust.Code)."
          },
          "params": {
            "type": "object",
            "additionalProperties": {
              "type": [
                "string",
                "integer"
              ]
            }
          }
        },
        "description": "A machine-readable explanation: a stable code and its parameters, no prose."
      },
      "LotTrust": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "snapshot",
          "queued",
          "holds",
          "history",
          "next_cursor"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "snapshot": {
            "oneOf": [
              {
                "type": "null"
              },
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "tier",
                  "computed",
                  "status",
                  "sealed",
                  "explanation",
                  "computed_at"
                ],
                "properties": {
                  "tier": {
                    "$ref": "#/components/schemas/TrustTier"
                  },
                  "computed": {
                    "$ref": "#/components/schemas/TrustTier"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "normal",
                      "on_hold"
                    ]
                  },
                  "sealed": {
                    "oneOf": [
                      {
                        "type": "null"
                      },
                      {
                        "type": "object",
                        "additionalProperties": false,
                        "required": [
                          "tier",
                          "at",
                          "basis"
                        ],
                        "properties": {
                          "tier": {
                            "$ref": "#/components/schemas/TrustTier"
                          },
                          "at": {
                            "type": "number"
                          },
                          "basis": {
                            "type": "string",
                            "enum": [
                              "transition",
                              "recorded_transition",
                              "migration"
                            ],
                            "description": "How the seal was taken: transition (inside the transaction that moved the lot past open), recorded_transition (a lot already past open at migration 21, sealed at its recorded close or pack time because no stored evidence of it is newer) or migration (such a lot with newer evidence, sealed at its first recompute after the migration, from the evidence then)."
                          }
                        }
                      }
                    ]
                  },
                  "explanation": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "reasons",
                      "steps"
                    ],
                    "properties": {
                      "reasons": {
                        "type": "array",
                        "items": {
                          "$ref": "#/components/schemas/TrustReason"
                        }
                      },
                      "steps": {
                        "type": "array",
                        "items": {
                          "type": "object",
                          "additionalProperties": false,
                          "required": [
                            "step",
                            "tier",
                            "reasons",
                            "sources"
                          ],
                          "properties": {
                            "step": {
                              "type": "string",
                              "enum": [
                                "registration",
                                "harvest",
                                "measurement",
                                "lab",
                                "packing",
                                "shipping"
                              ]
                            },
                            "tier": {
                              "$ref": "#/components/schemas/TrustTier"
                            },
                            "reasons": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/TrustReason"
                              }
                            },
                            "sources": {
                              "type": "array",
                              "items": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      }
                    }
                  },
                  "computed_at": {
                    "type": "number"
                  }
                }
              }
            ]
          },
          "queued": {
            "type": "boolean",
            "description": "The lot waits for a recompute."
          },
          "holds": {
            "type": "array",
            "maxItems": 20,
            "description": "The latest recorded holds, newest first.",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "kind",
                "status",
                "opened_at",
                "closed_at"
              ],
              "properties": {
                "id": {
                  "type": "integer"
                },
                "kind": {
                  "type": "string",
                  "enum": [
                    "report",
                    "quarantine",
                    "key_compromise",
                    "lab_failure",
                    "rejected_component"
                  ]
                },
                "status": {
                  "type": "string",
                  "enum": [
                    "open",
                    "escalated",
                    "resolved",
                    "withdrawn"
                  ]
                },
                "opened_at": {
                  "type": "number",
                  "description": "When the hold began (the evidence's own time)."
                },
                "closed_at": {
                  "type": [
                    "number",
                    "null"
                  ]
                }
              }
            }
          },
          "history": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "tier",
                "computed",
                "status",
                "sealed_tier",
                "cause",
                "computed_at"
              ],
              "properties": {
                "id": {
                  "type": "integer"
                },
                "tier": {
                  "$ref": "#/components/schemas/TrustTier"
                },
                "computed": {
                  "$ref": "#/components/schemas/TrustTier"
                },
                "status": {
                  "type": "string",
                  "enum": [
                    "normal",
                    "on_hold"
                  ]
                },
                "sealed_tier": {
                  "oneOf": [
                    {
                      "type": "null"
                    },
                    {
                      "$ref": "#/components/schemas/TrustTier"
                    }
                  ]
                },
                "cause": {
                  "type": "string"
                },
                "computed_at": {
                  "type": "number"
                }
              }
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "IssuerKey": {
        "type": "object",
        "description": "A facility's did:web issuer key (#34). The private key is never returned: it is stored encrypted under the deployment's key-encryption key. `key_id` is the DID URL a credential cites (`<did>#key-<n>`).",
        "required": [
          "facility",
          "n",
          "name",
          "did",
          "key_id",
          "alg",
          "public_jwk",
          "status",
          "created_by",
          "created_at",
          "retired_at",
          "revoked_at",
          "revoke_reason",
          "revoked_by"
        ],
        "additionalProperties": false,
        "properties": {
          "facility": {
            "type": "string"
          },
          "n": {
            "type": "integer",
            "minimum": 1,
            "description": "The key's number within the facility, never reused."
          },
          "name": {
            "type": "string",
            "pattern": "^key-[1-9][0-9]*$"
          },
          "did": {
            "type": "string",
            "pattern": "^did:web:[A-Za-z0-9.%:_-]{1,200}$",
            "description": "`did:web:<AGRITRACE_DID_DOMAIN>:<facility slug>`."
          },
          "key_id": {
            "type": "string",
            "maxLength": 260
          },
          "alg": {
            "const": "ES256"
          },
          "public_jwk": {
            "$ref": "#/components/schemas/PublicJwk"
          },
          "status": {
            "enum": [
              "active",
              "retired",
              "revoked"
            ],
            "description": "active: signs. retired: replaced by a rotation, still in the DID document. revoked: compromised, removed from the DID document."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "retired_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "compromise",
              null
            ]
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "facility": "VN-TGPH-021",
          "n": 1,
          "name": "key-1",
          "did": "did:web:txng.theio.vn:tanphu",
          "key_id": "did:web:txng.theio.vn:tanphu#key-1",
          "alg": "ES256",
          "public_jwk": {
            "kty": "EC",
            "crv": "P-256",
            "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
            "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
          },
          "status": "active",
          "created_by": "admin@coop.example",
          "created_at": 1790000000.5,
          "retired_at": null,
          "revoked_at": null,
          "revoke_reason": null,
          "revoked_by": null
        }
      },
      "PublicJwk": {
        "type": "object",
        "description": "A P-256 public key as a JWK (RFC 7518 §6.2.1).",
        "required": [
          "kty",
          "crv",
          "x",
          "y"
        ],
        "additionalProperties": false,
        "properties": {
          "kty": {
            "const": "EC"
          },
          "crv": {
            "const": "P-256"
          },
          "x": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]{43}$"
          },
          "y": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]{43}$"
          }
        },
        "example": {
          "kty": "EC",
          "crv": "P-256",
          "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
          "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
        }
      },
      "IssuerKeyList": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "description": "Every key of the facility by number (at most 100 per facility).",
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/IssuerKey"
            }
          }
        },
        "example": {
          "items": [
            {
              "facility": "VN-TGPH-021",
              "n": 1,
              "name": "key-1",
              "did": "did:web:txng.theio.vn:tanphu",
              "key_id": "did:web:txng.theio.vn:tanphu#key-1",
              "alg": "ES256",
              "public_jwk": {
                "kty": "EC",
                "crv": "P-256",
                "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
                "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
              },
              "status": "active",
              "created_by": "admin@coop.example",
              "created_at": 1790000000.5,
              "retired_at": null,
              "revoked_at": null,
              "revoke_reason": null,
              "revoked_by": null
            }
          ]
        }
      },
      "IssuerKeyRevoke": {
        "type": "object",
        "required": [
          "reason"
        ],
        "additionalProperties": false,
        "properties": {
          "reason": {
            "const": "compromise",
            "description": "Only a compromise revokes; a rotation generates a new key instead."
          }
        },
        "example": {
          "reason": "compromise"
        }
      },
      "DidDocument": {
        "type": "object",
        "description": "A DID document (W3C DID Core 1.0) of the did:web method: every active and retired key of the facility as a JsonWebKey2020 verification method, each also an assertion method; a revoked key is left out.",
        "required": [
          "@context",
          "id",
          "verificationMethod",
          "assertionMethod"
        ],
        "additionalProperties": false,
        "properties": {
          "@context": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "minItems": 1
          },
          "id": {
            "type": "string",
            "pattern": "^did:web:"
          },
          "verificationMethod": {
            "type": "array",
            "minItems": 1,
            "maxItems": 100,
            "items": {
              "type": "object",
              "required": [
                "id",
                "type",
                "controller",
                "publicKeyJwk"
              ],
              "additionalProperties": false,
              "properties": {
                "id": {
                  "type": "string"
                },
                "type": {
                  "const": "JsonWebKey2020"
                },
                "controller": {
                  "type": "string"
                },
                "publicKeyJwk": {
                  "$ref": "#/components/schemas/PublicJwk"
                }
              }
            }
          },
          "assertionMethod": {
            "type": "array",
            "minItems": 1,
            "maxItems": 100,
            "items": {
              "type": "string"
            }
          }
        },
        "example": {
          "@context": [
            "https://www.w3.org/ns/did/v1",
            "https://w3id.org/security/suites/jws-2020/v1"
          ],
          "id": "did:web:txng.theio.vn:tanphu",
          "verificationMethod": [
            {
              "id": "did:web:txng.theio.vn:tanphu#key-1",
              "type": "JsonWebKey2020",
              "controller": "did:web:txng.theio.vn:tanphu",
              "publicKeyJwk": {
                "kty": "EC",
                "crv": "P-256",
                "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
                "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
              }
            }
          ],
          "assertionMethod": [
            "did:web:txng.theio.vn:tanphu#key-1"
          ]
        }
      },
      "LotCloseRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "confirm_counts"
        ],
        "description": "What the operator confirms before signing: the lot's fruit records as the console showed them.",
        "properties": {
          "confirm_counts": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "fruits"
            ],
            "properties": {
              "fruits": {
                "type": "integer",
                "minimum": 0,
                "description": "The lot's fruit records, every status (409 when the lot has another number)."
              }
            }
          }
        },
        "example": {
          "confirm_counts": {
            "fruits": 128
          }
        }
      },
      "LotSeal": {
        "type": "object",
        "additionalProperties": false,
        "description": "A lot's seal (L10, #35): the signed credential of its manifest and what identifies it. `credential` is a compact JWS (VC-JOSE: protected header alg ES256, kid the issuer key's DID URL, typ vc+jwt, cty vc) whose payload is a W3C verifiable credential (VC 2.0, type AgriTraceLotSeal, issuer the facility's did:web) with the lot's manifest as credentialSubject: the lot's facts, every fruit record with the SHA-256 of its stored record and its bound envelope ids, every envelope of the lot with the SHA-256 of its stored payload and its signing key, the totals, the packing, the lab report, the shipment and the trust snapshot. The signature verifies with the key listed in `https://<domain>/<slug>/did.json`. `manifest_sha256` is the SHA-256 of the JWS payload bytes. `sealed_by` is an opaque operator id, never an email or a name: `user-<id>` for a signed-in user, `token-<id>` for an API token (its row id), `legacy-` and 16 hex digits of an HMAC under the server's secret for a legacy token. Times are Unix seconds.",
        "required": [
          "lot",
          "status",
          "sealed_at",
          "sealed_by",
          "key_id",
          "manifest_sha256",
          "fruit_count",
          "event_count",
          "credential"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "status": {
            "type": "string",
            "enum": [
              "closed",
              "packed",
              "shipped",
              "recalled",
              "withdrawn"
            ],
            "description": "The lot's status now."
          },
          "sealed_at": {
            "type": "number"
          },
          "sealed_by": {
            "type": "string",
            "pattern": "^(user-[0-9]+|token-[0-9]+|legacy-[0-9a-f]{16})$"
          },
          "key_id": {
            "type": "string",
            "maxLength": 260,
            "description": "The signing key's DID URL (`<did>#key-<n>`)."
          },
          "manifest_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "fruit_count": {
            "type": "integer",
            "minimum": 0,
            "maximum": 5000
          },
          "event_count": {
            "type": "integer",
            "minimum": 0,
            "maximum": 20000
          },
          "credential": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{86}$"
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "status": "shipped",
          "sealed_at": 1790754000.0,
          "sealed_by": "user-12",
          "key_id": "did:web:txng.theio.vn:tanphu#key-1",
          "manifest_sha256": "a869373f50f23727be3ef525863a48347c2c7d057119b62e02076adaa472d617",
          "fruit_count": 128,
          "event_count": 397,
          "credential": "eyJhbGciOiJFUzI1NiIsImN0eSI6InZjIiwia2lkIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSNrZXktMSIsInR5cCI6InZjK2p3dCJ9.eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvbnMvY3JlZGVudGlhbHMvdjIiXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdDozZjljMmE3YmU0MWQ0YzBhOWU4YjZkNWYxYTJjM2I0ZCIsImxvdCI6eyJjb2RlIjoiTE8tMjYwOTI4LTAxNCJ9fSwiaWQiOiJ1cm46YWdyaXRyYWNlOmxvdC1zZWFsOjNmOWMyYTdiZTQxZDRjMGE5ZThiNmQ1ZjFhMmMzYjRkIiwiaXNzdWVyIjoiZGlkOndlYjp0eG5nLnRoZWlvLnZuOnRhbnBodSIsInR5cGUiOlsiVmVyaWZpYWJsZUNyZWRlbnRpYWwiLCJBZ3JpVHJhY2VMb3RTZWFsIl0sInZhbGlkRnJvbSI6IjIwMjYtMDktMzBUMDc6NDA6MDBaIn0.kctQ5XyOhXmF4wAaMoRTYUURRmG5IFU2VbzNcoaa483PwGtJks5WlZMAGrcxteF8ryX2IaBEaL_wgq8vWqCWIw"
        }
      },
      "PublicEpcisDocument": {
        "type": "object",
        "required": [
          "@context",
          "type",
          "schemaVersion",
          "creationDate",
          "epcisBody"
        ],
        "description": "X3 (#44): an EPCIS 2.0 document (GS1 EPCIS 2.0.0, JSON-LD). Its full schema is GS1's (https://ref.gs1.org/standards/epcis/2.0.0/epcis-json-schema.json); this names only its frame. `@context` is the GS1 context, then this platform's `agri:` namespace.",
        "properties": {
          "@context": {
            "type": "array",
            "prefixItems": [
              {
                "const": "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld"
              },
              {
                "type": "object",
                "description": "This platform's context: the `agri:` namespace."
              }
            ],
            "minItems": 2,
            "maxItems": 2
          },
          "type": {
            "const": "EPCISDocument"
          },
          "schemaVersion": {
            "const": "2.0"
          },
          "creationDate": {
            "type": "string",
            "description": "The seal time, UTC."
          },
          "epcisBody": {
            "type": "object",
            "required": [
              "eventList"
            ],
            "properties": {
              "eventList": {
                "type": "array",
                "items": {
                  "type": "object"
                }
              }
            }
          }
        }
      },
      "PublicCredential": {
        "type": "string",
        "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{86}$",
        "description": "X3 (#44): a VC-JOSE compact JWS (W3C Securing Verifiable Credentials using JOSE and COSE, Recommendation 2025-05-15): protected header {alg ES256, kid: the issuer key's DID URL, typ vc+jwt, cty vc}, payload a VC 2.0 credential, signature r || s (64 bytes, so 86 base64url characters). The payload is a UNTP 0.7.0 credential (`@context` [https://www.w3.org/ns/credentials/v2, https://vocabulary.uncefact.org/untp/0.7.0/context/]) for a lot sealed since #162: a Digital Product Passport, or the packing facility's Digital Facility Record; a passport sealed before is a UNTP Digital Product Passport 0.6.1 (`@context` [https://www.w3.org/ns/credentials/v2, https://test.uncefact.org/vocabulary/untp/dpp/0.6.1/]), served as stored. See /developers/downloads/verify.md.",
        "x-sdk-description": "X3 (#44): a VC-JOSE compact JWS (W3C Securing Verifiable Credentials using JOSE and COSE, Recommendation 2025-05-15): protected header {alg ES256, kid: the issuer key's DID URL, typ vc+jwt, cty vc}, payload a VC 2.0 credential that is a UNTP Digital Product Passport 0.6.1 (`@context` [https://www.w3.org/ns/credentials/v2, https://test.uncefact.org/vocabulary/untp/dpp/0.6.1/]), signature r || s (64 bytes, so 86 base64url characters). See /developers/downloads/verify.md."
      },
      "PublicConformityCredential": {
        "type": "string",
        "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{86}$",
        "description": "#142: a VC-JOSE compact JWS (W3C Securing Verifiable Credentials using JOSE and COSE, Recommendation 2025-05-15): protected header {alg ES256, kid: the lab key's DID URL `did:web:<domain>:labs:<lab code>#<kid>`, typ vc+jwt, cty vc}, payload a VC 2.0 credential that is a UNTP Digital Conformity Credential 0.6.1 (`@context` [https://www.w3.org/ns/credentials/v2, https://test.uncefact.org/vocabulary/untp/dcc/0.6.1/]), signature r || s (64 bytes, so 86 base64url characters). See /developers/downloads/verify.md."
      },
      "ReportChallenge": {
        "type": "object",
        "description": "A proof-of-work challenge for a public mismatch report (#46, report_challenge.py). Find a `solution` (1 to 32 ASCII letters and digits; a decimal counter will do) such that SHA-256 of `<challenge>:<solution>` (UTF-8) starts with `difficulty` zero bits, and send both with the report within `expires_in` seconds. Signed by the backend (`<id>.<bits>.<expires>.<HMAC-SHA256>`), single-use (a challenge files one report) and refused once the deployment's difficulty (AGRITRACE_REPORT_POW_BITS) changes.",
        "additionalProperties": false,
        "required": [
          "challenge",
          "difficulty",
          "expires_in"
        ],
        "properties": {
          "challenge": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}\\.[0-9]{1,2}\\.[0-9]{1,12}\\.[0-9a-f]{64}$"
          },
          "difficulty": {
            "type": "integer",
            "minimum": 1,
            "maximum": 28
          },
          "expires_in": {
            "type": "integer",
            "minimum": 1
          }
        },
        "example": {
          "challenge": "9f1c2e7a5b3d4c6e8f0a1b2c3d4e5f60.18.1790000300.3b0f6a1c9d2e4f5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c",
          "difficulty": 18,
          "expires_in": 300
        }
      },
      "ReportCategory": {
        "type": "string",
        "description": "What does not match: `label_peeled` (the label was peeled or replaced), `scanned_many` (the code was scanned many times: a copied label is suspected), `ripeness_off` (the ripeness does not match the record), `other`.",
        "enum": [
          "label_peeled",
          "scanned_many",
          "ripeness_off",
          "other"
        ]
      },
      "ReportSubmission": {
        "type": "object",
        "description": "A public mismatch report on a public fruit. No other field is accepted (no photo: no public upload route exists). `note` keeps line breaks and no other control character; `contact` is one line. Both are trimmed; an empty contact is none. The contact is stored for staff triage only, never returned on a public route, and erased 90 days after the report is resolved.",
        "additionalProperties": false,
        "required": [
          "publicId",
          "category",
          "challenge",
          "solution"
        ],
        "properties": {
          "publicId": {
            "type": "string",
            "minLength": 1,
            "description": "The public id of the fruit (its page's)."
          },
          "category": {
            "$ref": "#/components/schemas/ReportCategory"
          },
          "note": {
            "type": "string",
            "maxLength": 1000
          },
          "contact": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "challenge": {
            "type": "string",
            "description": "A ReportChallenge's `challenge`."
          },
          "solution": {
            "type": "string",
            "pattern": "^[0-9A-Za-z]{1,32}$"
          }
        },
        "example": {
          "publicId": "73879f17d0930440809333f141385eb6",
          "category": "label_peeled",
          "note": "Tem bị bóc ở cuống.",
          "contact": "zalo 0901 234 567",
          "challenge": "9f1c2e7a5b3d4c6e8f0a1b2c3d4e5f60.18.1790000300.3b0f6a1c9d2e4f5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c",
          "solution": "184022"
        }
      },
      "ReportReceipt": {
        "type": "object",
        "description": "A report was received. Nothing of the report is echoed. #177: `fruit` and `lot` are the current public status of the reported fruit and of its lot (the report's hold), read from the origin when the report was filed, so the page can show them at once although an edge-cached record may still show the old status; null when the record is not public.",
        "additionalProperties": false,
        "required": [
          "status",
          "fruit",
          "lot"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "received"
            ]
          },
          "fruit": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicCurrentStatus"
              },
              {
                "type": "null"
              }
            ]
          },
          "lot": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicCurrentStatus"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "example": {
          "status": "received",
          "fruit": {
            "status": "under_review",
            "status_since": "2026-10-10T09:30:00+07:00",
            "status_reason": null,
            "tier": "self_declared"
          },
          "lot": {
            "status": "under_review",
            "status_since": "2026-10-10T09:30:00+07:00",
            "status_reason": null,
            "tier": "self_declared"
          }
        }
      },
      "PublicCurrentStatus": {
        "type": "object",
        "description": "#177: the current public status of a record, as its own record states it now: `status`, `status_since`, `status_reason` and `trust.tier` (as `tier`).",
        "additionalProperties": false,
        "required": [
          "status",
          "status_since",
          "status_reason",
          "tier"
        ],
        "properties": {
          "status": {
            "$ref": "#/components/schemas/PublicStatus"
          },
          "status_since": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicIsoDateTime"
              },
              {
                "type": "null"
              }
            ]
          },
          "status_reason": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/RecallReason"
              },
              {
                "type": "null"
              }
            ]
          },
          "tier": {
            "$ref": "#/components/schemas/PublicTrustTier"
          }
        }
      },
      "Report": {
        "type": "object",
        "description": "A public mismatch report as staff triage sees it, with the contact (null when none was given or once erased, 90 days after the resolution). Times are Unix seconds.",
        "additionalProperties": false,
        "required": [
          "id",
          "fruit",
          "lot",
          "category",
          "note",
          "contact",
          "status",
          "outcome",
          "created_at",
          "resolved_at"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "fruit": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code",
              "public_id"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "public_id": {
                "type": "string"
              }
            }
          },
          "lot": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code",
              "public_id"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "public_id": {
                "type": "string"
              }
            }
          },
          "category": {
            "$ref": "#/components/schemas/ReportCategory"
          },
          "note": {
            "type": "string",
            "maxLength": 1000
          },
          "contact": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "resolved"
            ]
          },
          "outcome": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "confirmed",
              "unfounded",
              "duplicate",
              null
            ]
          },
          "created_at": {
            "type": "number"
          },
          "resolved_at": {
            "type": [
              "number",
              "null"
            ]
          }
        },
        "example": {
          "id": 12,
          "fruit": {
            "code": "Q-0928-014-0003",
            "public_id": "73879f17d0930440809333f141385eb6"
          },
          "lot": {
            "code": "LO-260928-014",
            "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
          },
          "category": "label_peeled",
          "note": "Tem bị bóc ở cuống.",
          "contact": "zalo 0901 234 567",
          "status": "open",
          "outcome": null,
          "created_at": 1790000000.5,
          "resolved_at": null
        }
      },
      "ReportPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/Report"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 12,
              "fruit": {
                "code": "Q-0928-014-0003",
                "public_id": "73879f17d0930440809333f141385eb6"
              },
              "lot": {
                "code": "LO-260928-014",
                "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
              },
              "category": "label_peeled",
              "note": "Tem bị bóc ở cuống.",
              "contact": "zalo 0901 234 567",
              "status": "open",
              "outcome": null,
              "created_at": 1790000000.5,
              "resolved_at": null
            }
          ],
          "next_cursor": null
        }
      },
      "ReportResolution": {
        "type": "object",
        "description": "`confirmed` (the mismatch was real and has been dealt with), `unfounded` (the fruit matches its record) or `duplicate` (another report covers it). Every outcome resolves the report.",
        "additionalProperties": false,
        "required": [
          "outcome"
        ],
        "properties": {
          "outcome": {
            "type": "string",
            "enum": [
              "confirmed",
              "unfounded",
              "duplicate"
            ]
          }
        },
        "example": {
          "outcome": "unfounded"
        }
      },
      "LotCloseCheck": {
        "type": "object",
        "additionalProperties": false,
        "description": "A lot's close check (O6, #64): the operator console's close dialog. Times are Unix seconds.",
        "required": [
          "lot",
          "status",
          "sealed",
          "counts",
          "sessions",
          "issuer_key",
          "timestamping",
          "blockers",
          "seal"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "status": {
            "enum": [
              "draft",
              "open",
              "paused",
              "closed",
              "packed",
              "shipped",
              "recalled",
              "withdrawn"
            ]
          },
          "sealed": {
            "type": "boolean",
            "description": "Whether the lot has its seal."
          },
          "counts": {
            "type": "object",
            "additionalProperties": false,
            "description": "The lot's final counts.",
            "required": [
              "fruits",
              "pending_review",
              "awaiting_device",
              "quarantined_envelopes",
              "cartons"
            ],
            "properties": {
              "fruits": {
                "type": "integer",
                "minimum": 0,
                "description": "Fruit records of the lot: the number `confirm_counts.fruits` confirms."
              },
              "pending_review": {
                "type": "integer",
                "minimum": 0,
                "description": "Fruits in review (a bound envelope is quarantined): the close refuses them."
              },
              "awaiting_device": {
                "type": "integer",
                "minimum": 0,
                "description": "Fruits still awaiting their device record."
              },
              "quarantined_envelopes": {
                "type": "integer",
                "minimum": 0,
                "maximum": 20001,
                "description": "Quarantined envelopes of the lot, counted up to 20001 (a bounded read)."
              },
              "cartons": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 0,
                "description": "Packed cartons; null until the lot is packed."
              }
            }
          },
          "sessions": {
            "type": "object",
            "additionalProperties": false,
            "description": "Measurement sessions of the lot not closed yet; the close closes a paused one.",
            "required": [
              "open",
              "paused"
            ],
            "properties": {
              "open": {
                "type": "integer",
                "minimum": 0
              },
              "paused": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "issuer_key": {
            "type": [
              "string",
              "null"
            ],
            "description": "The DID URL of the facility's active issuer key, the one the close signs with; null without one."
          },
          "timestamping": {
            "type": "boolean",
            "description": "Whether an external timestamp authority (RFC 3161) is configured: the seal's manifest hash is then timestamped by the periodic job."
          },
          "blockers": {
            "type": "array",
            "description": "Why the close cannot be confirmed now, in this order; empty when nothing blocks. `envelopes_not_synced`: a fruit awaits its device record or an envelope of the lot is quarantined.",
            "items": {
              "type": "string",
              "enum": [
                "already_sealed",
                "not_sealable",
                "fruits_pending_review",
                "session_open",
                "envelopes_not_synced",
                "no_issuer_key",
                "lot_too_large"
              ]
            }
          },
          "seal": {
            "oneOf": [
              {
                "type": "null"
              },
              {
                "type": "object",
                "additionalProperties": false,
                "description": "The lot's seal (never its credential: GET /v1/lots/{lot}/manifest).",
                "required": [
                  "key_id",
                  "manifest_sha256",
                  "sealed_at",
                  "fruit_count",
                  "event_count",
                  "timestamp"
                ],
                "properties": {
                  "key_id": {
                    "type": "string",
                    "description": "DID URL of the key that signed."
                  },
                  "manifest_sha256": {
                    "type": "string",
                    "pattern": "^[0-9a-f]{64}$",
                    "description": "SHA-256 of the credential's payload bytes."
                  },
                  "sealed_at": {
                    "type": "number"
                  },
                  "fruit_count": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "event_count": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "timestamp": {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "status",
                      "gen_time"
                    ],
                    "description": "The seal's external timestamp: `verified` once a token was verified (with its genTime), `pending` while the job waits for one, `off` when no timestamp authority is configured.",
                    "properties": {
                      "status": {
                        "type": "string",
                        "enum": [
                          "off",
                          "pending",
                          "verified"
                        ]
                      },
                      "gen_time": {
                        "type": [
                          "number",
                          "null"
                        ]
                      }
                    }
                  }
                }
              }
            ]
          }
        }
      },
      "PublicLotFruit": {
        "description": "U5 (#58): one public fruit of a lot, from an explicit allowlist. Never a tenant, database id, fruit number, session, line, operator, envelope, device id or key.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "public_id",
          "code",
          "ripeness_level",
          "model_confidence",
          "weight_kg",
          "grade",
          "tier",
          "sensory_override",
          "recording_url"
        ],
        "properties": {
          "public_id": {
            "$ref": "#/components/schemas/PublicCode",
            "description": "The fruit's public id (its record: /{locale}/q/{public_id})."
          },
          "code": {
            "$ref": "#/components/schemas/PublicCode",
            "description": "The fruit code printed on its label."
          },
          "ripeness_level": {
            "type": "integer",
            "minimum": 1,
            "maximum": 4,
            "description": "The effective level (L3): the operator's sensory level when overridden, else the device's."
          },
          "model_confidence": {
            "type": "number",
            "minimum": 0,
            "maximum": 1,
            "description": "The device model's confidence, 0..1."
          },
          "weight_kg": {
            "type": "number",
            "exclusiveMinimum": 0,
            "description": "The bound scale reading, kg."
          },
          "grade": {
            "type": "string",
            "enum": [
              "A",
              "B",
              "reject"
            ],
            "description": "The grade (L3)."
          },
          "tier": {
            "$ref": "#/components/schemas/PublicTrustTier",
            "description": "As the fruit record's `trust.tier`: min(the lot's read-time tier, the fruit's own record tier), capped by the fruit's own quarantine hold. A sensory override makes it Self-declared."
          },
          "sensory_override": {
            "type": "boolean",
            "description": "An operator replaced the device's level (always true in group `overridden`, false in `measured`)."
          },
          "recording_url": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicSameOriginPath"
              },
              {
                "type": "null"
              }
            ],
            "description": "The original tap recording (GET /v1/public/fruits/{publicId}/recordings/{sha256}); null when the knock has no stored recording."
          }
        }
      },
      "PublicLotFruitPage": {
        "description": "U5 (#58): one page of a public lot's fruits in one group, in fruit order.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "group",
          "total",
          "items",
          "next_cursor"
        ],
        "properties": {
          "lot": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "public_id",
              "code"
            ],
            "properties": {
              "public_id": {
                "$ref": "#/components/schemas/PublicCode"
              },
              "code": {
                "$ref": "#/components/schemas/PublicCode"
              }
            }
          },
          "group": {
            "type": "string",
            "enum": [
              "measured",
              "overridden"
            ]
          },
          "total": {
            "type": "integer",
            "minimum": 0,
            "description": "Public fruits of the lot in this group."
          },
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/PublicLotFruit"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        },
        "example": {
          "lot": {
            "public_id": "074eb09b371fc71c380da235aea9c14a",
            "code": "LO-260928-014"
          },
          "group": "measured",
          "total": 120,
          "items": [
            {
              "public_id": "5c1f0e2a9b7d4c3e8f6a1b2c3d4e5f60",
              "code": "Q-014-0001",
              "ripeness_level": 3,
              "model_confidence": 0.91,
              "weight_kg": 2.84,
              "grade": "A",
              "tier": "device_recorded",
              "sensory_override": false,
              "recording_url": "/v1/public/fruits/5c1f0e2a9b7d4c3e8f6a1b2c3d4e5f60/recordings/9f2c0d5ab1e7c3f4a6b8d0e2f4a6c8e0b2d4f6a8c0e2a4c6e8a0c2e4a6c8e0b2"
            },
            {
              "public_id": "6d2a1f3b0c8e5d4f9a7b2c3d4e5f6a71",
              "code": "Q-014-0002",
              "ripeness_level": 2,
              "model_confidence": 0.88,
              "weight_kg": 2.94,
              "grade": "A",
              "tier": "device_recorded",
              "sensory_override": false,
              "recording_url": null
            }
          ],
          "next_cursor": "eyJuIjoyfQ"
        }
      },
      "RecallReason": {
        "description": "The reason category of a recall or withdrawal (P5, #41), the only part of it the public pages show: contamination (a chemical residue or contaminant over its limit), pathogen (microbial), foreign_matter, labelling (wrong or missing label or origin information), quality (spoilage or a quality defect), regulatory (a market's rule not met), traceability (the evidence cannot be relied on), other.",
        "type": "string",
        "enum": [
          "contamination",
          "pathogen",
          "foreign_matter",
          "labelling",
          "quality",
          "regulatory",
          "traceability",
          "other"
        ]
      },
      "LotRecallRequest": {
        "description": "A recall or withdrawal of the whole lot (P5, #41). `kind` recall moves the lot to `recalled`, withdrawal to `withdrawn`; `scope` is the recall depth (21 CFR 7.42(b)(1)); `note` is staff text, never public, never in the audit row or the outbound notice.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "kind",
          "reason",
          "scope"
        ],
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "recall",
              "withdrawal"
            ]
          },
          "reason": {
            "$ref": "#/components/schemas/RecallReason"
          },
          "scope": {
            "type": "string",
            "enum": [
              "consumer",
              "retail",
              "wholesale"
            ]
          },
          "note": {
            "type": "string",
            "maxLength": 1000,
            "default": ""
          }
        }
      },
      "LotRecall": {
        "description": "The recall or withdrawal of a lot (P5, #41) and its outbound notice, stored for the outbound adapter (#90) and not sent yet. `recalled_by` is an opaque operator id (`user-<id>`, `token-<id>` or `legacy-<keyed hash>`), never an email or a name; `cartons` and `shipments` are what the trace found at the recall.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "kind",
          "status",
          "reason",
          "scope",
          "note",
          "prior_status",
          "recalled_by",
          "recalled_at",
          "cartons",
          "shipments",
          "notice"
        ],
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "recall",
              "withdrawal"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "recalled",
              "withdrawn"
            ]
          },
          "reason": {
            "$ref": "#/components/schemas/RecallReason"
          },
          "scope": {
            "type": "string",
            "enum": [
              "consumer",
              "retail",
              "wholesale"
            ]
          },
          "note": {
            "type": "string",
            "maxLength": 1000
          },
          "prior_status": {
            "type": "string",
            "enum": [
              "draft",
              "open",
              "paused",
              "closed",
              "packed",
              "shipped"
            ]
          },
          "recalled_by": {
            "type": "string"
          },
          "recalled_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "cartons": {
            "type": "integer",
            "minimum": 0
          },
          "shipments": {
            "type": "integer",
            "minimum": 0
          },
          "notice": {
            "oneOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "target",
                  "status",
                  "attempts",
                  "created_at",
                  "delivered_at"
                ],
                "properties": {
                  "target": {
                    "type": "string",
                    "enum": [
                      "national_portal"
                    ]
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "pending",
                      "delivered"
                    ]
                  },
                  "attempts": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "created_at": {
                    "type": "number"
                  },
                  "delivered_at": {
                    "oneOf": [
                      {
                        "type": "number"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "RecallList": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "total",
          "notices_pending"
        ],
        "description": "#322: the company's recalls and withdrawals, newest first, with their counts.",
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "lot",
                "recall"
              ],
              "properties": {
                "lot": {
                  "type": "string",
                  "description": "Lot code."
                },
                "recall": {
                  "$ref": "#/components/schemas/LotRecall"
                }
              }
            }
          },
          "total": {
            "type": "integer",
            "minimum": 0,
            "description": "Every recall and withdrawal of the company (`items` lists the newest 100)."
          },
          "notices_pending": {
            "type": "integer",
            "minimum": 0,
            "description": "Their outbound notices not sent yet."
          }
        }
      },
      "LotTrace": {
        "description": "The affected set of a lot (P5, #41): backward to its facility, growing area and harvest; forward to its cartons (all counted, at most 500 listed in carton order, `truncated` when more exist) and the shipment carrying it, and through the chain of lot merges (#91) to every lot holding its fruit: the lot a merge produced from it, the lot a merge produced from that one, and so on (a merged lot can be closed and merged again), at most 8 merges: those lots' cartons are counted and listed with the lot's own (after them, in chain order), and the shipment is the first found along the chain, the lot's own first; the other lots of the tenant from the same growing area and harvest date (at most 50, by code). The harvest is the lot's accepted signed harvest event carrying a mass (`signed_event`), else the growing area's declaration for the harvest date (`area_declaration`: the whole area's kg), else only the date. On request (getLotTrace `merges=1`, #259) the trace also names the lots the merges link: `forward.merged_into`, the lots of the chain after this one in chain order, `backward.merged_from`, the input lots of the merge that produced this one (empty when no merge did), and each listed carton's `lot`.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "recall",
          "backward",
          "forward",
          "related_lots"
        ],
        "properties": {
          "lot": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code",
              "status",
              "product",
              "variety",
              "public_id"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "status": {
                "type": "string",
                "enum": [
                  "draft",
                  "open",
                  "paused",
                  "closed",
                  "packed",
                  "shipped",
                  "recalled",
                  "withdrawn"
                ]
              },
              "product": {
                "type": "string"
              },
              "variety": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "public_id": {
                "type": "string"
              }
            }
          },
          "recall": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/LotRecall"
              },
              {
                "type": "null"
              }
            ]
          },
          "backward": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "facility",
              "growing_area",
              "harvest"
            ],
            "properties": {
              "facility": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "code",
                  "name"
                ],
                "properties": {
                  "code": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              },
              "growing_area": {
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "code",
                      "commune",
                      "district",
                      "province"
                    ],
                    "properties": {
                      "code": {
                        "type": "string"
                      },
                      "commune": {
                        "oneOf": [
                          {
                            "type": "string"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "district": {
                        "oneOf": [
                          {
                            "type": "string"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "province": {
                        "oneOf": [
                          {
                            "type": "string"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      }
                    }
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "harvest": {
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "date",
                      "at",
                      "kg",
                      "source"
                    ],
                    "properties": {
                      "date": {
                        "type": "string",
                        "format": "date"
                      },
                      "at": {
                        "oneOf": [
                          {
                            "type": "number"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "kg": {
                        "oneOf": [
                          {
                            "type": "number"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "source": {
                        "oneOf": [
                          {
                            "type": "string",
                            "enum": [
                              "signed_event",
                              "area_declaration"
                            ]
                          },
                          {
                            "type": "null"
                          }
                        ]
                      }
                    }
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "merged_from": {
                "description": "#259, only with getLotTrace `merges=1`: the input lots of the merge that produced this lot, by code, each with the kg the merge took from it; empty when no merge produced it. A merge has at most 50 inputs.",
                "type": "array",
                "maxItems": 50,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "status",
                    "quantity_kg"
                  ],
                  "properties": {
                    "code": {
                      "type": "string"
                    },
                    "status": {
                      "type": "string"
                    },
                    "quantity_kg": {
                      "type": "number"
                    }
                  }
                },
                "x-not-in-sdk": true
              }
            }
          },
          "forward": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "cartons",
              "shipment"
            ],
            "properties": {
              "cartons": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "count",
                  "fruits",
                  "net_mass_kg",
                  "items",
                  "truncated"
                ],
                "properties": {
                  "count": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "fruits": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "net_mass_kg": {
                    "oneOf": [
                      {
                        "type": "number"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "truncated": {
                    "type": "boolean"
                  },
                  "items": {
                    "type": "array",
                    "maxItems": 500,
                    "items": {
                      "type": "object",
                      "additionalProperties": false,
                      "required": [
                        "code",
                        "carton_no",
                        "fruits",
                        "net_mass_kg",
                        "shipment"
                      ],
                      "properties": {
                        "code": {
                          "type": "string"
                        },
                        "carton_no": {
                          "type": "integer"
                        },
                        "fruits": {
                          "type": "integer"
                        },
                        "net_mass_kg": {
                          "oneOf": [
                            {
                              "type": "number"
                            },
                            {
                              "type": "null"
                            }
                          ]
                        },
                        "shipment": {
                          "oneOf": [
                            {
                              "type": "string"
                            },
                            {
                              "type": "null"
                            }
                          ]
                        },
                        "lot": {
                          "description": "#259, only with getLotTrace `merges=1`: the code of the lot the carton belongs to (this lot, or a lot of `merged_into`).",
                          "type": "string",
                          "x-not-in-sdk": true
                        }
                      }
                    }
                  }
                }
              },
              "shipment": {
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "code",
                      "facility",
                      "status",
                      "container",
                      "destination",
                      "border_gate",
                      "departed_at",
                      "cartons"
                    ],
                    "properties": {
                      "code": {
                        "type": "string"
                      },
                      "facility": {
                        "type": "string"
                      },
                      "status": {
                        "type": "string",
                        "enum": [
                          "open",
                          "departed"
                        ]
                      },
                      "container": {
                        "type": "string"
                      },
                      "destination": {
                        "type": "string"
                      },
                      "border_gate": {
                        "type": "string"
                      },
                      "departed_at": {
                        "oneOf": [
                          {
                            "type": "number"
                          },
                          {
                            "type": "null"
                          }
                        ]
                      },
                      "cartons": {
                        "type": "integer",
                        "minimum": 0
                      }
                    }
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "merged_into": {
                "description": "#259, only with getLotTrace `merges=1`: the lots holding this lot's fruit through the chain of merges, in chain order: the lot a merge produced from this one, the lot a merge produced from that one, and so on (at most 8); empty when no merge consumed it.",
                "type": "array",
                "maxItems": 8,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "status"
                  ],
                  "properties": {
                    "code": {
                      "type": "string"
                    },
                    "status": {
                      "type": "string"
                    }
                  }
                },
                "x-not-in-sdk": true
              }
            }
          },
          "related_lots": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "items",
              "truncated"
            ],
            "properties": {
              "truncated": {
                "type": "boolean"
              },
              "items": {
                "type": "array",
                "maxItems": 50,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "status",
                    "harvest_date"
                  ],
                  "properties": {
                    "code": {
                      "type": "string"
                    },
                    "status": {
                      "type": "string"
                    },
                    "harvest_date": {
                      "type": "string",
                      "format": "date"
                    }
                  }
                }
              }
            }
          }
        },
        "x-sdk-description": "The affected set of a lot (P5, #41): backward to its facility, growing area and harvest; forward to its cartons (all counted, at most 500 listed in carton order, `truncated` when more exist) and the shipment carrying it; the other lots of the tenant from the same growing area and harvest date (at most 50, by code). The harvest is the lot's accepted signed harvest event carrying a mass (`signed_event`), else the growing area's declaration for the harvest date (`area_declaration`: the whole area's kg), else only the date."
      },
      "RecallExport": {
        "description": "The FSMA-204-style sortable record of a lot's affected records (P5, #41): one row per critical tracking event in time order: harvesting (at the growing area: the signed harvest event's mass, else the area's declared kg for the date, else empty), initial_packing (one per carton, at the lot's facility and pack time) and shipping (one per carton on the departed shipment, at the departure facility), and transformation (#91: a lot merge the lot took part in, at the merge's facility and time: one row per input lot with the kg taken from it and one of the lot it produced with its kg). Through the chain of merges the record follows the fruit both ways: backward, the merge that produced the lot, the merges that produced its inputs, and so on, with each input lot's harvest (breadth first, at most 8 levels and 64 merges); forward, the merge that consumed the lot, the merge that consumed the lot it produced, and so on (at most 8 merges), with the cartons and shipment of each lot they produced. A row of another lot than the requested one carries that lot's code and product. Times are local (Asia/Ho_Chi_Minh, +07:00). Columns: traceability_lot_code, critical_tracking_event, event_date, event_time, location, location_description, product_description, quantity, unit_of_measure, carton, fruit_count, shipment, container, destination, border_gate, recall_kind, recall_reason. An empty cell is an empty string. Each row property documents its unit and format. At most 186,855 rows.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "format",
          "lot",
          "generated_at",
          "recall",
          "columns",
          "rows"
        ],
        "properties": {
          "format": {
            "type": "string",
            "const": "agritrace-recall-export/1"
          },
          "lot": {
            "type": "string"
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          },
          "recall": {
            "oneOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "kind",
                  "reason",
                  "scope",
                  "recalled_at"
                ],
                "properties": {
                  "kind": {
                    "type": "string",
                    "enum": [
                      "recall",
                      "withdrawal"
                    ]
                  },
                  "reason": {
                    "$ref": "#/components/schemas/RecallReason"
                  },
                  "scope": {
                    "type": "string",
                    "enum": [
                      "consumer",
                      "retail",
                      "wholesale"
                    ]
                  },
                  "recalled_at": {
                    "type": "string",
                    "format": "date-time"
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          },
          "columns": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "traceability_lot_code",
                "critical_tracking_event",
                "event_date",
                "event_time",
                "location",
                "location_description",
                "product_description",
                "quantity",
                "unit_of_measure",
                "carton",
                "fruit_count",
                "shipment",
                "container",
                "destination",
                "border_gate",
                "recall_kind",
                "recall_reason"
              ]
            }
          },
          "rows": {
            "type": "array",
            "maxItems": 186855,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "traceability_lot_code",
                "critical_tracking_event",
                "event_date",
                "event_time",
                "location",
                "location_description",
                "product_description",
                "quantity",
                "unit_of_measure",
                "carton",
                "fruit_count",
                "shipment",
                "container",
                "destination",
                "border_gate",
                "recall_kind",
                "recall_reason"
              ],
              "properties": {
                "traceability_lot_code": {
                  "type": "string",
                  "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$",
                  "description": "The lot code (the traceability lot code of the row): the requested lot's, or, on a row of a lot merge (#91), that of the lot the row is about.",
                  "x-sdk-description": "The lot code (the traceability lot code of every row)."
                },
                "critical_tracking_event": {
                  "type": "string",
                  "enum": [
                    "harvesting",
                    "initial_packing",
                    "shipping",
                    "transformation"
                  ],
                  "description": "The critical tracking event: harvesting (at the growing area), transformation (#91: a lot merge, at its facility), initial_packing (one per carton, at the lot's facility) or shipping (one per carton on the departed shipment, at the departure facility).",
                  "x-sdk-enum": [
                    "harvesting",
                    "initial_packing",
                    "shipping"
                  ],
                  "x-sdk-description": "The critical tracking event: harvesting (at the growing area), initial_packing (one per carton, at the lot's facility) or shipping (one per carton on the departed shipment, at the departure facility)."
                },
                "event_date": {
                  "type": "string",
                  "format": "date",
                  "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
                  "description": "The event's local date (Asia/Ho_Chi_Minh), YYYY-MM-DD."
                },
                "event_time": {
                  "type": "string",
                  "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]\\+07:00$|^$",
                  "description": "The event's local time with its offset, whole seconds, hh:mm:ss+07:00; empty for a harvest known only by its date (an area declaration, or no harvest event)."
                },
                "location": {
                  "type": "string",
                  "maxLength": 64,
                  "description": "Where the event happened: the growing area code (harvesting) or the facility code (transformation, initial_packing, shipping); empty for a harvest of a lot without a growing area.",
                  "x-sdk-description": "Where the event happened: the growing area code (harvesting) or the facility code (initial_packing, shipping); empty for a harvest of a lot without a growing area."
                },
                "location_description": {
                  "type": "string",
                  "description": "The growing area's commune, district and province, comma-separated (harvesting), or the facility's name (initial_packing, and shipping from the lot's facility); empty when unknown. #273: a growing area coded by official administrative unit codes has its commune and province instead (Viet Nam has had no district level since 2025-07-01).",
                  "x-sdk-description": "The growing area's commune, district and province, comma-separated (harvesting), or the facility's name (initial_packing, and shipping from the lot's facility); empty when unknown."
                },
                "product_description": {
                  "type": "string",
                  "description": "The product and variety, space-separated (e.g. `durian Ri6`), of the lot the row is about.",
                  "x-sdk-description": "The lot's product and variety, space-separated (e.g. `durian Ri6`)."
                },
                "quantity": {
                  "description": "The quantity in kilograms (unit_of_measure kg), at most 3 decimals: the signed harvest event's mass or the area's declared kg for the date (harvesting), the carton's net mass (initial_packing, shipping), or the kg a merge took from an input lot or gave the lot it produced (transformation); empty without a quantity.",
                  "oneOf": [
                    {
                      "type": "number",
                      "minimum": 0
                    },
                    {
                      "type": "string",
                      "enum": [
                        ""
                      ]
                    }
                  ],
                  "x-sdk-description": "The quantity in kilograms (unit_of_measure kg), at most 3 decimals: the signed harvest event's mass or the area's declared kg for the date (harvesting), or the carton's net mass (initial_packing, shipping); empty without a quantity."
                },
                "unit_of_measure": {
                  "type": "string",
                  "enum": [
                    "kg",
                    ""
                  ],
                  "description": "`kg` when quantity is given, else empty."
                },
                "carton": {
                  "type": "string",
                  "pattern": "^C-[0-9]{3,19}-[0-9]{4}$|^$",
                  "description": "The carton code `C-<lot seq>-<carton number>` (initial_packing, shipping); empty for harvesting."
                },
                "fruit_count": {
                  "description": "The number of fruits in the carton (initial_packing, shipping); empty for harvesting.",
                  "oneOf": [
                    {
                      "type": "integer",
                      "minimum": 0
                    },
                    {
                      "type": "string",
                      "enum": [
                        ""
                      ]
                    }
                  ]
                },
                "shipment": {
                  "type": "string",
                  "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$|^$",
                  "description": "The shipment code (shipping); empty otherwise."
                },
                "container": {
                  "type": "string",
                  "pattern": "^[A-Z]{3}[UJZ][0-9]{7}$|^$",
                  "description": "The ISO 6346 container number (shipping); empty otherwise."
                },
                "destination": {
                  "type": "string",
                  "pattern": "^[A-Z]{2}$|^$",
                  "description": "The destination market, ISO 3166-1 alpha-2 (shipping); empty otherwise."
                },
                "border_gate": {
                  "type": "string",
                  "maxLength": 100,
                  "description": "The border gate the shipment heads for, a display string (shipping); empty otherwise."
                },
                "recall_kind": {
                  "type": "string",
                  "enum": [
                    "recall",
                    "withdrawal",
                    ""
                  ],
                  "description": "The lot's recall kind on every row: recall or withdrawal; empty while the lot is not recalled."
                },
                "recall_reason": {
                  "description": "The recall's reason category on every row (RecallReason); empty while the lot is not recalled.",
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/RecallReason"
                    },
                    {
                      "type": "string",
                      "enum": [
                        ""
                      ]
                    }
                  ]
                }
              }
            },
            "x-sdk-maxItems": 19999
          }
        },
        "x-sdk-description": "The FSMA-204-style sortable record of a lot's affected records (P5, #41): one row per critical tracking event in time order: harvesting (at the growing area: the signed harvest event's mass, else the area's declared kg for the date, else empty), initial_packing (one per carton, at the lot's facility and pack time) and shipping (one per carton on the departed shipment, at the departure facility). Times are local (Asia/Ho_Chi_Minh, +07:00). Columns: traceability_lot_code, critical_tracking_event, event_date, event_time, location, location_description, product_description, quantity, unit_of_measure, carton, fruit_count, shipment, container, destination, border_gate, recall_kind, recall_reason. An empty cell is an empty string. Each row property documents its unit and format. At most 19,999 rows."
      },
      "ApiToken": {
        "type": "object",
        "description": "A machine API token of the tenant as the admin console lists it: never the token itself, never its hash (only its SHA-256 is stored; the token is shown once, by POST /v1/api-tokens). Unix seconds.",
        "additionalProperties": false,
        "required": [
          "id",
          "name",
          "role",
          "created_by",
          "created_at",
          "last_used_at",
          "expires_at",
          "revoked_at",
          "revoke_reason",
          "revoked_by",
          "status"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "name": {
            "type": "string",
            "description": "The operator's label (not unique).",
            "maxLength": 64
          },
          "role": {
            "type": "string",
            "enum": [
              "platform_admin",
              "tenant_admin",
              "operator",
              "lab",
              "auditor"
            ],
            "description": "The role the token acts with (tokens made with the users CLI may hold any role)."
          },
          "created_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who created it: a user's email, or `cli`."
          },
          "created_at": {
            "type": "number"
          },
          "last_used_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "The last authenticated use, to the minute; null: never."
          },
          "expires_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "null: never expires."
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "expired",
              "revoked"
            ],
            "description": "At the server clock: revoked, else expired once `expires_at` passed, else active."
          }
        },
        "example": {
          "id": 7,
          "name": "erp-sync",
          "role": "operator",
          "created_by": "admin@coop.example",
          "created_at": 1790000000.5,
          "last_used_at": null,
          "expires_at": 1797776000.5,
          "revoked_at": null,
          "revoke_reason": null,
          "revoked_by": null,
          "status": "active"
        }
      },
      "ApiTokenPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/ApiToken"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 7,
              "name": "erp-sync",
              "role": "operator",
              "created_by": "admin@coop.example",
              "created_at": 1790000000.5,
              "last_used_at": null,
              "expires_at": 1797776000.5,
              "revoked_at": null,
              "revoke_reason": null,
              "revoked_by": null,
              "status": "active"
            }
          ],
          "next_cursor": null
        }
      },
      "ApiTokenCreate": {
        "type": "object",
        "description": "`role`: operator, auditor or tenant_admin (platform_admin and lab tokens are made with the users CLI only). `expires_in_days`: whole days from 1 to 3650; absent or null, the token never expires.",
        "additionalProperties": false,
        "required": [
          "name",
          "role"
        ],
        "properties": {
          "name": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"
          },
          "role": {
            "type": "string",
            "enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "expires_in_days": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 3650
          }
        },
        "example": {
          "name": "erp-sync",
          "role": "operator",
          "expires_in_days": 90
        }
      },
      "ApiTokenCreated": {
        "type": "object",
        "description": "The new token and, in `secret`, the token itself: this response is the only place it ever appears (`Authorization: Bearer <secret>`). Store it now; a lost token is revoked and replaced.",
        "additionalProperties": false,
        "required": [
          "token",
          "secret"
        ],
        "properties": {
          "token": {
            "$ref": "#/components/schemas/ApiToken"
          },
          "secret": {
            "type": "string",
            "pattern": "^agt_[A-Za-z0-9_-]{43}$"
          }
        },
        "example": {
          "token": {
            "id": 7,
            "name": "erp-sync",
            "role": "operator",
            "created_by": "admin@coop.example",
            "created_at": 1790000000.5,
            "last_used_at": null,
            "expires_at": 1797776000.5,
            "revoked_at": null,
            "revoke_reason": null,
            "revoked_by": null,
            "status": "active"
          },
          "secret": "agt_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGx"
        }
      },
      "ApiTokenRevoke": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Why it is revoked, one line (e.g. leaked, no longer used)."
          }
        },
        "example": {
          "reason": "leaked in a CI log"
        }
      },
      "OAuthClient": {
        "type": "object",
        "description": "An OAuth2 API client of the tenant as the admin console lists it: never the secret, never its hash. Unix seconds.",
        "additionalProperties": false,
        "required": [
          "id",
          "client_id",
          "name",
          "role",
          "scopes",
          "facilities",
          "created_by",
          "created_at",
          "last_token_at",
          "revoked_at",
          "revoke_reason",
          "revoked_by",
          "status"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "client_id": {
            "type": "string",
            "pattern": "^agc_[A-Za-z0-9_-]{22}$",
            "description": "The public client identifier the integration authenticates with."
          },
          "name": {
            "type": "string",
            "maxLength": 64,
            "description": "The operator's label (not unique)."
          },
          "role": {
            "type": "string",
            "enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "scopes": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "enum": [
                "aggregate_read",
                "attachment_read",
                "attachment_upload",
                "command_read",
                "device_admin",
                "device_command",
                "device_read",
                "envelope_read",
                "epcis_capture",
                "facility_edit",
                "facility_read",
                "fruit_action",
                "grading_rule_read",
                "grading_rule_write",
                "growing_area_edit",
                "growing_area_read",
                "issuer_key_admin",
                "lot_read",
                "lot_recall",
                "lot_write",
                "market_limit_read",
                "recall_read",
                "records_export",
                "report_triage",
                "review",
                "tenant_read",
                "trace_read",
                "webhook_admin"
              ],
              "description": "A permission: the name of the route policy it opens (rbac.OAUTH_SCOPES)."
            }
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "An operator client's facility codes; null: every facility."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "last_token_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When it last got a token; null: never."
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "revoked"
            ]
          }
        },
        "example": {
          "id": 3,
          "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
          "name": "erp-sync",
          "role": "operator",
          "scopes": [
            "lot_read",
            "lot_write"
          ],
          "facilities": [
            "VN-TGPH-021"
          ],
          "created_by": "admin@coop.example",
          "created_at": 1790000000.5,
          "last_token_at": null,
          "revoked_at": null,
          "revoke_reason": null,
          "revoked_by": null,
          "status": "active"
        }
      },
      "OAuthClientPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/OAuthClient"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 3,
              "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
              "name": "erp-sync",
              "role": "operator",
              "scopes": [
                "lot_read",
                "lot_write"
              ],
              "facilities": [
                "VN-TGPH-021"
              ],
              "created_by": "admin@coop.example",
              "created_at": 1790000000.5,
              "last_token_at": null,
              "revoked_at": null,
              "revoke_reason": null,
              "revoked_by": null,
              "status": "active"
            }
          ],
          "next_cursor": null
        }
      },
      "OAuthClientCreate": {
        "type": "object",
        "description": "`role`: tenant_admin, operator or auditor. `scopes`: distinct permissions the role can hold (credential management, platform and lab permissions are never granted). `facilities`: an operator client only, 1 to 64 distinct facility codes of the tenant; absent or null, every facility.",
        "additionalProperties": false,
        "required": [
          "name",
          "role",
          "scopes"
        ],
        "properties": {
          "name": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"
          },
          "role": {
            "type": "string",
            "enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "scopes": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "enum": [
                "aggregate_read",
                "attachment_read",
                "attachment_upload",
                "command_read",
                "device_admin",
                "device_command",
                "device_read",
                "envelope_read",
                "epcis_capture",
                "facility_edit",
                "facility_read",
                "fruit_action",
                "grading_rule_read",
                "grading_rule_write",
                "growing_area_edit",
                "growing_area_read",
                "issuer_key_admin",
                "lot_read",
                "lot_recall",
                "lot_write",
                "market_limit_read",
                "recall_read",
                "records_export",
                "report_triage",
                "review",
                "tenant_read",
                "trace_read",
                "webhook_admin"
              ],
              "description": "A permission: the name of the route policy it opens (rbac.OAUTH_SCOPES)."
            }
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "minItems": 1,
            "maxItems": 64,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "minLength": 1
            }
          }
        },
        "example": {
          "name": "erp-sync",
          "role": "operator",
          "scopes": [
            "lot_read",
            "lot_write"
          ],
          "facilities": [
            "VN-TGPH-021"
          ]
        }
      },
      "OAuthClientCreated": {
        "type": "object",
        "description": "The new client and, in `client_secret`, its secret: this response is the only place it ever appears. Store it now; a lost secret means revoking the client and registering a new one.",
        "additionalProperties": false,
        "required": [
          "client",
          "client_secret"
        ],
        "properties": {
          "client": {
            "$ref": "#/components/schemas/OAuthClient"
          },
          "client_secret": {
            "type": "string",
            "pattern": "^acs_[A-Za-z0-9_-]{43}$"
          }
        },
        "example": {
          "client": {
            "id": 3,
            "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
            "name": "erp-sync",
            "role": "operator",
            "scopes": [
              "lot_read",
              "lot_write"
            ],
            "facilities": [
              "VN-TGPH-021"
            ],
            "created_by": "admin@coop.example",
            "created_at": 1790000000.5,
            "last_token_at": null,
            "revoked_at": null,
            "revoke_reason": null,
            "revoked_by": null,
            "status": "active"
          },
          "client_secret": "acs_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGx"
        }
      },
      "OAuthClientRevoke": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Why it is revoked, one line."
          }
        },
        "example": {
          "reason": "contract ended"
        }
      },
      "OAuthClientDetail": {
        "type": "object",
        "description": "#205: an API client as the credential view shows it: the fields of OAuthClient plus its expiry, allowed sources, last use and write scopes. Never the secret, its hash or a client address. Unix seconds.",
        "additionalProperties": false,
        "required": [
          "id",
          "client_id",
          "name",
          "role",
          "scopes",
          "facilities",
          "created_by",
          "created_at",
          "last_token_at",
          "revoked_at",
          "revoke_reason",
          "revoked_by",
          "status",
          "expires_at",
          "expired",
          "allowed_ips",
          "last_used_at",
          "last_used_ip_hash",
          "write_scopes",
          "broad_scope"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "client_id": {
            "type": "string",
            "pattern": "^agc_[A-Za-z0-9_-]{22}$",
            "description": "The public client identifier the integration authenticates with."
          },
          "name": {
            "type": "string",
            "maxLength": 64,
            "description": "The operator's label (not unique)."
          },
          "role": {
            "type": "string",
            "enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "scopes": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "enum": [
                "aggregate_read",
                "attachment_read",
                "attachment_upload",
                "command_read",
                "device_admin",
                "device_command",
                "device_read",
                "envelope_read",
                "epcis_capture",
                "facility_edit",
                "facility_read",
                "fruit_action",
                "grading_rule_read",
                "grading_rule_write",
                "growing_area_edit",
                "growing_area_read",
                "issuer_key_admin",
                "lot_read",
                "lot_recall",
                "lot_write",
                "market_limit_read",
                "recall_read",
                "records_export",
                "report_triage",
                "review",
                "tenant_read",
                "trace_read",
                "webhook_admin"
              ],
              "description": "A permission: the name of the route policy it opens (rbac.OAUTH_SCOPES)."
            }
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "An operator client's facility codes; null: every facility."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "last_token_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When it last got a token; null: never."
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "revoked"
            ]
          },
          "expires_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When the client stops getting tokens and its tokens stop working (Unix seconds); null only for a client an older server registered, which counts as expired."
          },
          "expired": {
            "type": "boolean",
            "description": "True from `expires_at` on (or without one): renew it to use it again."
          },
          "allowed_ips": {
            "type": [
              "array",
              "null"
            ],
            "minItems": 1,
            "maxItems": 20,
            "items": {
              "type": "string",
              "maxLength": 64
            },
            "description": "The networks (CIDR form, IPv4 or IPv6) the client may call from; null: any source."
          },
          "last_used_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When it last got a token or called the API (calls are recorded at most once a minute, and shown within seconds); null: never."
          },
          "last_used_ip_hash": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "A keyed hash (HMAC-SHA256) of the address of that last use, never the address: equal values mean the same source."
          },
          "write_scopes": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "aggregate_read",
                "attachment_read",
                "attachment_upload",
                "command_read",
                "device_admin",
                "device_command",
                "device_read",
                "envelope_read",
                "epcis_capture",
                "facility_edit",
                "facility_read",
                "fruit_action",
                "grading_rule_read",
                "grading_rule_write",
                "growing_area_edit",
                "growing_area_read",
                "issuer_key_admin",
                "lot_read",
                "lot_recall",
                "lot_write",
                "market_limit_read",
                "recall_read",
                "records_export",
                "report_triage",
                "review",
                "tenant_read",
                "trace_read",
                "webhook_admin"
              ],
              "description": "A permission: the name of the route policy it opens (rbac.OAUTH_SCOPES)."
            },
            "description": "The client's scopes that open a write (a route other than GET)."
          },
          "broad_scope": {
            "type": "boolean",
            "description": "True when `write_scopes` is not empty: the client can change the company's records."
          }
        },
        "example": {
          "id": 3,
          "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
          "name": "erp-sync",
          "role": "operator",
          "scopes": [
            "lot_read",
            "lot_write"
          ],
          "facilities": [
            "VN-TGPH-021"
          ],
          "created_by": "admin@coop.example",
          "created_at": 1790000000.5,
          "last_token_at": 1790003600.5,
          "revoked_at": null,
          "revoke_reason": null,
          "revoked_by": null,
          "status": "active",
          "expires_at": 1821536000.5,
          "expired": false,
          "allowed_ips": [
            "203.0.113.0/24"
          ],
          "last_used_at": 1790003660.5,
          "last_used_ip_hash": "5b1f0c3e9a7d2b4c6e8f0a1b3c5d7e9f1a2b4c6d8e0f1a3b5c7d9e1f2a4b6c8d",
          "write_scopes": [
            "lot_write"
          ],
          "broad_scope": true
        }
      },
      "OAuthClientDetailPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/OAuthClientDetail"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 3,
              "client_id": "agc_V2hhdCBhIGNsaWVudCBpZA",
              "name": "erp-sync",
              "role": "operator",
              "scopes": [
                "lot_read",
                "lot_write"
              ],
              "facilities": [
                "VN-TGPH-021"
              ],
              "created_by": "admin@coop.example",
              "created_at": 1790000000.5,
              "last_token_at": 1790003600.5,
              "revoked_at": null,
              "revoke_reason": null,
              "revoked_by": null,
              "status": "active",
              "expires_at": 1821536000.5,
              "expired": false,
              "allowed_ips": [
                "203.0.113.0/24"
              ],
              "last_used_at": 1790003660.5,
              "last_used_ip_hash": "5b1f0c3e9a7d2b4c6e8f0a1b3c5d7e9f1a2b4c6d8e0f1a3b5c7d9e1f2a4b6c8d",
              "write_scopes": [
                "lot_write"
              ],
              "broad_scope": true
            }
          ],
          "next_cursor": null
        }
      },
      "OAuthClientRenew": {
        "type": "object",
        "description": "#205: the new lifetime, counted from now. Absent: 365 days.",
        "additionalProperties": false,
        "properties": {
          "expires_in_days": {
            "type": "integer",
            "minimum": 1,
            "maximum": 730
          }
        },
        "example": {
          "expires_in_days": 365
        }
      },
      "OAuthClientAllowedIps": {
        "type": "object",
        "description": "#205: 1 to 20 distinct networks in CIDR form, IPv4 or IPv6 (a bare address is its /32 or /128; host bits set are refused), or null for any source. The key is required.",
        "additionalProperties": false,
        "required": [
          "allowed_ips"
        ],
        "properties": {
          "allowed_ips": {
            "type": [
              "array",
              "null"
            ],
            "minItems": 1,
            "maxItems": 20,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "minLength": 1,
              "maxLength": 64
            }
          }
        },
        "example": {
          "allowed_ips": [
            "203.0.113.0/24",
            "2001:db8::/32"
          ]
        }
      },
      "OAuthTokenRequest": {
        "type": "object",
        "description": "RFC 6749 §4.4.2. `client_id` and `client_secret` only when the client does not use HTTP Basic. `scope`: space-separated permissions, a subset of the client's; absent, all of them.",
        "required": [
          "grant_type"
        ],
        "properties": {
          "grant_type": {
            "type": "string",
            "enum": [
              "client_credentials"
            ]
          },
          "scope": {
            "type": "string"
          },
          "client_id": {
            "type": "string"
          },
          "client_secret": {
            "type": "string"
          }
        },
        "example": {
          "grant_type": "client_credentials",
          "scope": "lot_read"
        }
      },
      "OAuthRevokeRequest": {
        "type": "object",
        "description": "RFC 7009 §2.1. `client_id` and `client_secret` only when the client does not use HTTP Basic.",
        "required": [
          "token"
        ],
        "properties": {
          "token": {
            "type": "string"
          },
          "token_type_hint": {
            "type": "string"
          },
          "client_id": {
            "type": "string"
          },
          "client_secret": {
            "type": "string"
          }
        },
        "example": {
          "token": "ago_VGhpcyBpcyBhbiBleGFtcGxlIGFjY2VzcyB0b2tlbiE",
          "token_type_hint": "access_token"
        }
      },
      "OAuthError": {
        "type": "object",
        "description": "The error body of the OAuth2 endpoints (RFC 6749 §5.2): `error` the RFC error code, equal to `code`, and `error_description` the text. A request refused before the endpoint ran (a bad X-Request-Id, the rate limit, an Idempotency-Key header) gets the API's usual body, `error` and `code` only.",
        "additionalProperties": false,
        "required": [
          "error",
          "code"
        ],
        "properties": {
          "error": {
            "type": "string"
          },
          "error_description": {
            "type": "string"
          },
          "code": {
            "type": "string"
          }
        },
        "example": {
          "error": "invalid_client",
          "error_description": "client authentication failed",
          "code": "invalid_client"
        }
      },
      "OAuthToken": {
        "type": "object",
        "description": "RFC 6749 §5.1.",
        "additionalProperties": false,
        "required": [
          "access_token",
          "token_type",
          "expires_in",
          "scope"
        ],
        "properties": {
          "access_token": {
            "type": "string",
            "pattern": "^ago_[A-Za-z0-9_-]{43}$"
          },
          "token_type": {
            "type": "string",
            "enum": [
              "Bearer"
            ]
          },
          "expires_in": {
            "type": "integer",
            "minimum": 1,
            "description": "Seconds."
          },
          "scope": {
            "type": "string",
            "description": "The scopes granted, space separated."
          }
        },
        "example": {
          "access_token": "ago_VGhpcyBpcyBhbiBleGFtcGxlIGFjY2VzcyB0b2tlbiE",
          "token_type": "Bearer",
          "expires_in": 900,
          "scope": "lot_read lot_write"
        }
      },
      "GradingRuleVersion": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "version",
          "rules",
          "updated_at",
          "updated_by"
        ],
        "description": "One version of a variety's rules: numbered 1, 2, ... per rule, as each PUT wrote it.",
        "properties": {
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "rules": {
            "$ref": "#/components/schemas/GradingRules"
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_by": {
            "type": "string",
            "description": "Who wrote this version."
          }
        },
        "example": {
          "version": 2,
          "rules": {
            "a_levels": [
              2,
              3
            ],
            "reject_levels": [
              1,
              4
            ],
            "a_weight_kg": [
              [
                2.0,
                5.0
              ]
            ],
            "a_min_confidence": 0.8,
            "eating_window": [
              {
                "band": "ambient",
                "end_days": 7,
                "level": 1,
                "max_days": 30,
                "min_days": 0,
                "start_days": 5,
                "warning": "immature"
              },
              {
                "band": "ambient",
                "end_days": 6,
                "level": 2,
                "max_days": 1,
                "min_days": 0,
                "start_days": 4,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 4,
                "level": 2,
                "max_days": 3,
                "min_days": 2,
                "start_days": 3,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 2,
                "level": 2,
                "max_days": 30,
                "min_days": 4,
                "start_days": 1,
                "warning": "eat_soon"
              },
              {
                "band": "ambient",
                "end_days": 4,
                "level": 3,
                "max_days": 1,
                "min_days": 0,
                "start_days": 3,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 3,
                "level": 3,
                "max_days": 3,
                "min_days": 2,
                "start_days": 2,
                "warning": null
              },
              {
                "band": "ambient",
                "end_days": 1,
                "level": 3,
                "max_days": 30,
                "min_days": 4,
                "start_days": 0,
                "warning": "eat_soon"
              },
              {
                "band": "ambient",
                "end_days": 1,
                "level": 4,
                "max_days": 30,
                "min_days": 0,
                "start_days": 0,
                "warning": "overripe"
              },
              {
                "band": "14-18C",
                "end_days": 10,
                "level": 1,
                "max_days": 30,
                "min_days": 0,
                "start_days": 7,
                "warning": "immature"
              },
              {
                "band": "14-18C",
                "end_days": 8,
                "level": 2,
                "max_days": 30,
                "min_days": 0,
                "start_days": 5,
                "warning": null
              },
              {
                "band": "14-18C",
                "end_days": 6,
                "level": 3,
                "max_days": 30,
                "min_days": 0,
                "start_days": 4,
                "warning": null
              },
              {
                "band": "14-18C",
                "end_days": 2,
                "level": 4,
                "max_days": 30,
                "min_days": 0,
                "start_days": 0,
                "warning": "overripe"
              },
              {
                "band": "10-13C",
                "end_days": 12,
                "level": 1,
                "max_days": 30,
                "min_days": 0,
                "start_days": 9,
                "warning": "immature"
              },
              {
                "band": "10-13C",
                "end_days": 10,
                "level": 2,
                "max_days": 30,
                "min_days": 0,
                "start_days": 7,
                "warning": null
              },
              {
                "band": "10-13C",
                "end_days": 8,
                "level": 3,
                "max_days": 30,
                "min_days": 0,
                "start_days": 5,
                "warning": null
              },
              {
                "band": "10-13C",
                "end_days": 2,
                "level": 4,
                "max_days": 30,
                "min_days": 0,
                "start_days": 0,
                "warning": "overripe"
              }
            ]
          },
          "updated_at": 1790000000.5,
          "updated_by": "admin@coop.example"
        }
      },
      "GradingRuleHistory": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "variety",
          "items",
          "next_cursor"
        ],
        "properties": {
          "variety": {
            "type": "string",
            "maxLength": 64
          },
          "items": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/GradingRuleVersion"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "variety": "Ri6",
          "items": [
            {
              "version": 2,
              "rules": {
                "a_levels": [
                  2,
                  3
                ],
                "reject_levels": [
                  1,
                  4
                ],
                "a_weight_kg": [
                  [
                    2.0,
                    5.0
                  ]
                ],
                "a_min_confidence": 0.8,
                "eating_window": [
                  {
                    "band": "ambient",
                    "end_days": 7,
                    "level": 1,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 5,
                    "warning": "immature"
                  },
                  {
                    "band": "ambient",
                    "end_days": 6,
                    "level": 2,
                    "max_days": 1,
                    "min_days": 0,
                    "start_days": 4,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 4,
                    "level": 2,
                    "max_days": 3,
                    "min_days": 2,
                    "start_days": 3,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 2,
                    "level": 2,
                    "max_days": 30,
                    "min_days": 4,
                    "start_days": 1,
                    "warning": "eat_soon"
                  },
                  {
                    "band": "ambient",
                    "end_days": 4,
                    "level": 3,
                    "max_days": 1,
                    "min_days": 0,
                    "start_days": 3,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 3,
                    "level": 3,
                    "max_days": 3,
                    "min_days": 2,
                    "start_days": 2,
                    "warning": null
                  },
                  {
                    "band": "ambient",
                    "end_days": 1,
                    "level": 3,
                    "max_days": 30,
                    "min_days": 4,
                    "start_days": 0,
                    "warning": "eat_soon"
                  },
                  {
                    "band": "ambient",
                    "end_days": 1,
                    "level": 4,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 0,
                    "warning": "overripe"
                  },
                  {
                    "band": "14-18C",
                    "end_days": 10,
                    "level": 1,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 7,
                    "warning": "immature"
                  },
                  {
                    "band": "14-18C",
                    "end_days": 8,
                    "level": 2,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 5,
                    "warning": null
                  },
                  {
                    "band": "14-18C",
                    "end_days": 6,
                    "level": 3,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 4,
                    "warning": null
                  },
                  {
                    "band": "14-18C",
                    "end_days": 2,
                    "level": 4,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 0,
                    "warning": "overripe"
                  },
                  {
                    "band": "10-13C",
                    "end_days": 12,
                    "level": 1,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 9,
                    "warning": "immature"
                  },
                  {
                    "band": "10-13C",
                    "end_days": 10,
                    "level": 2,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 7,
                    "warning": null
                  },
                  {
                    "band": "10-13C",
                    "end_days": 8,
                    "level": 3,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 5,
                    "warning": null
                  },
                  {
                    "band": "10-13C",
                    "end_days": 2,
                    "level": 4,
                    "max_days": 30,
                    "min_days": 0,
                    "start_days": 0,
                    "warning": "overripe"
                  }
                ]
              },
              "updated_at": 1790000000.5,
              "updated_by": "admin@coop.example"
            }
          ],
          "next_cursor": null
        }
      },
      "MarketLimit": {
        "type": "object",
        "description": "One market limit entry: the maximum (`kind` max, `value` in mg/kg) or ban (`kind` banned, no value) of an analyte in a product for a destination market, from `valid_from` (Asia/Ho_Chi_Minh) until a later entry of the same market, product and analyte supersedes it. `status` on today's date: in_force (the entry that applies today), scheduled (from a later date) or superseded. Entries are never edited: a lab result keeps a copy of the limit it was judged with.",
        "additionalProperties": false,
        "required": [
          "id",
          "market",
          "product",
          "analyte",
          "kind",
          "value",
          "unit",
          "valid_from",
          "source",
          "created_at",
          "created_by",
          "status"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "ISO 3166-1 alpha-2."
          },
          "product": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "As lots.product."
          },
          "analyte": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$"
          },
          "kind": {
            "type": "string",
            "enum": [
              "max",
              "banned"
            ]
          },
          "value": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "description": "The maximum; null for a ban."
          },
          "unit": {
            "type": "string",
            "enum": [
              "mg/kg"
            ]
          },
          "valid_from": {
            "type": "string",
            "format": "date"
          },
          "source": {
            "type": "string",
            "minLength": 1,
            "maxLength": 1000,
            "description": "The regulation it cites."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "created_by": {
            "type": "string",
            "description": "Who recorded it (`migration`: the seeded entries)."
          },
          "status": {
            "type": "string",
            "enum": [
              "in_force",
              "scheduled",
              "superseded"
            ]
          }
        },
        "example": {
          "id": 1,
          "market": "CN",
          "product": "durian",
          "analyte": "cadmium",
          "kind": "max",
          "value": 0.05,
          "unit": "mg/kg",
          "valid_from": "2023-06-30",
          "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)",
          "created_at": 1790000000.5,
          "created_by": "migration",
          "status": "in_force"
        }
      },
      "MarketLimitPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "today",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/MarketLimit"
            }
          },
          "today": {
            "type": "string",
            "format": "date",
            "description": "The date `status` is computed for."
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 1,
              "market": "CN",
              "product": "durian",
              "analyte": "cadmium",
              "kind": "max",
              "value": 0.05,
              "unit": "mg/kg",
              "valid_from": "2023-06-30",
              "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)",
              "created_at": 1790000000.5,
              "created_by": "migration",
              "status": "in_force"
            },
            {
              "id": 2,
              "market": "CN",
              "product": "durian",
              "analyte": "auramine_o",
              "kind": "banned",
              "value": null,
              "unit": "mg/kg",
              "valid_from": "2025-01-10",
              "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted; GACC requires an auramine O test report with every durian shipment since 2025-01-10 (https://www.producereport.com/article/vietnamese-durian-exports-china-halted-over-missing-test-reports)",
              "created_at": 1790000000.5,
              "created_by": "migration",
              "status": "in_force"
            }
          ],
          "today": "2026-09-30",
          "next_cursor": null
        }
      },
      "MarketLimitCreate": {
        "type": "object",
        "description": "A new entry. `value` is required for `max` (above 0, at most 1000 mg/kg) and must be absent or null for `banned`. `valid_from` from today (Asia/Ho_Chi_Minh) to 10 years ahead: an entry never reaches back. The unit is always mg/kg.",
        "additionalProperties": false,
        "required": [
          "market",
          "product",
          "analyte",
          "kind",
          "valid_from",
          "source"
        ],
        "properties": {
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$"
          },
          "product": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "analyte": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$"
          },
          "kind": {
            "type": "string",
            "enum": [
              "max",
              "banned"
            ]
          },
          "value": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "maximum": 1000
          },
          "valid_from": {
            "type": "string",
            "format": "date"
          },
          "source": {
            "type": "string",
            "minLength": 1,
            "maxLength": 1000
          }
        },
        "example": {
          "market": "CN",
          "product": "durian",
          "analyte": "cadmium",
          "kind": "max",
          "value": 0.03,
          "valid_from": "2026-10-15",
          "source": "GB 2762-2026, 4.2 cadmium, fresh fruit 0.03 mg/kg"
        }
      },
      "AdminHealth": {
        "description": "What /healthz reports (Health) plus the database, the external timestamp authority and the issuer key store, for the admin health page. Each certificate's `not_after` is written in UTC with `Z` (e.g. 2030-01-02T03:04:05Z).",
        "allOf": [
          {
            "$ref": "#/components/schemas/Health"
          },
          {
            "type": "object",
            "required": [
              "db",
              "tsa",
              "issuer_keys"
            ],
            "properties": {
              "db": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "dialect",
                  "schema_version",
                  "expected_schema_version",
                  "round_trip_ms"
                ],
                "properties": {
                  "dialect": {
                    "type": "string",
                    "enum": [
                      "sqlite",
                      "postgresql"
                    ]
                  },
                  "schema_version": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "expected_schema_version": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "The version this backend release migrates to."
                  },
                  "round_trip_ms": {
                    "type": "number",
                    "minimum": 0,
                    "description": "One `SELECT 1` as this request measured it."
                  }
                }
              },
              "tsa": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "mode",
                  "host",
                  "pending",
                  "failing",
                  "verified"
                ],
                "description": "RFC 3161 external timestamps of lot seals (#36).",
                "properties": {
                  "mode": {
                    "type": "string",
                    "enum": [
                      "on",
                      "off"
                    ],
                    "description": "off: AGRITRACE_TSA_URL is unset (or read-only mode)."
                  },
                  "host": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "The TSA's host only, never its path."
                  },
                  "pending": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Seals waiting for a timestamp."
                  },
                  "failing": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Pending seals whose last attempt failed."
                  },
                  "verified": {
                    "type": "integer",
                    "minimum": 0
                  }
                }
              },
              "issuer_keys": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "available"
                ],
                "properties": {
                  "available": {
                    "type": "boolean",
                    "description": "false: AGRITRACE_ISSUER_KEK is not configured, so no issuer key can be generated or sign."
                  }
                }
              }
            }
          }
        ],
        "example": {
          "ok": true,
          "outbound_backlog": {
            "national": 0
          },
          "certificates": [
            {
              "path": "/certs/gw-01.pem",
              "subject": "gw-01",
              "not_after": "2027-01-01T00:00:00+00:00",
              "remaining_s": 7776000,
              "remaining_fraction": 0.5,
              "expired": false
            }
          ],
          "mqtt": {
            "broker": "emqx:8883",
            "connected": true
          },
          "db": {
            "dialect": "postgresql",
            "schema_version": 30,
            "expected_schema_version": 30,
            "round_trip_ms": 0.8
          },
          "tsa": {
            "mode": "on",
            "host": "freetsa.org",
            "pending": 1,
            "failing": 1,
            "verified": 42
          },
          "issuer_keys": {
            "available": true
          }
        }
      },
      "LabPortalKeyCreate": {
        "type": "object",
        "required": [
          "kid"
        ],
        "additionalProperties": false,
        "properties": {
          "kid": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",
            "description": "Key id; one namespace with device and gateway keys."
          }
        },
        "example": {
          "kid": "LAB-VN-118.portal"
        }
      },
      "LabPortalEntry": {
        "type": "object",
        "description": "What a lab portal user enters (#73): the report number, the SHA-256 of the report's PDF and the results, exactly as a signed `LabReportSubmission` carries them. The server adds the version, the lab, the sampling and the signing time and signs the document with the lab's active server-held key.",
        "required": [
          "report_no",
          "report_sha256",
          "results"
        ],
        "additionalProperties": false,
        "properties": {
          "report_no": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",
            "description": "The lab's report number, once per lab."
          },
          "report_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the report's PDF original."
          },
          "results": {
            "type": "array",
            "minItems": 1,
            "maxItems": 384,
            "items": {
              "oneOf": [
                {
                  "$ref": "#/components/schemas/LabReportResultSubmission"
                },
                {
                  "$ref": "#/components/schemas/LabOriginResultSubmission"
                }
              ]
            }
          }
        },
        "example": {
          "report_no": "KN-260929-0071",
          "report_sha256": "5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f",
          "results": [
            {
              "sample": 1,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS"
            },
            {
              "sample": 1,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS"
            },
            {
              "sample": 2,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS"
            },
            {
              "sample": 2,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS"
            },
            {
              "sample": 3,
              "analyte": "cadmium",
              "outcome": "measured",
              "value": 0.018,
              "unit": "mg/kg",
              "lod": 0.002,
              "method": "ICP-MS"
            },
            {
              "sample": 3,
              "analyte": "auramine_o",
              "outcome": "not_detected",
              "unit": "mg/kg",
              "lod": 0.001,
              "method": "LC-MS/MS"
            }
          ]
        }
      },
      "LabAssignmentDetail": {
        "type": "object",
        "required": [
          "id",
          "exporter",
          "lot",
          "facility",
          "analytes",
          "sample_count",
          "selected_at",
          "samples",
          "report",
          "portal_key"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer"
          },
          "exporter": {
            "type": "string",
            "description": "Name of the tenant that owns the lot."
          },
          "lot": {
            "type": "object",
            "required": [
              "code",
              "product",
              "variety",
              "harvest_date"
            ],
            "additionalProperties": false,
            "properties": {
              "code": {
                "type": "string"
              },
              "product": {
                "type": "string"
              },
              "variety": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "harvest_date": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          },
          "facility": {
            "type": "object",
            "required": [
              "code",
              "name",
              "address",
              "province",
              "district"
            ],
            "additionalProperties": false,
            "properties": {
              "code": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "address": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "province": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "district": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          },
          "analytes": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SampleAnalyte"
            }
          },
          "sample_count": {
            "type": "integer",
            "minimum": 1
          },
          "selected_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "samples": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SampleItem"
            }
          },
          "report": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/LabReport"
              },
              {
                "type": "null"
              }
            ]
          },
          "portal_key": {
            "oneOf": [
              {
                "type": "object",
                "required": [
                  "kid"
                ],
                "additionalProperties": false,
                "properties": {
                  "kid": {
                    "type": "string"
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "example": {
          "id": 41,
          "exporter": "HTX Ngũ Hiệp",
          "lot": {
            "code": "LO-260928-014",
            "product": "durian",
            "variety": "Ri6",
            "harvest_date": "2026-09-27"
          },
          "facility": {
            "code": "VN-TGPH-021",
            "name": "Cơ sở đóng gói Tân Phú",
            "address": null,
            "province": "Tiền Giang",
            "district": "Cai Lậy"
          },
          "analytes": [
            "cadmium",
            "auramine_o"
          ],
          "sample_count": 3,
          "selected_at": 1790000000.5,
          "samples": [
            {
              "k": 1,
              "fruit": "Q-014-0017",
              "status": "selected"
            },
            {
              "k": 2,
              "fruit": "Q-014-0062",
              "status": "selected"
            },
            {
              "k": 3,
              "fruit": "Q-014-0109",
              "status": "selected"
            }
          ],
          "report": null,
          "portal_key": {
            "kid": "LAB-VN-118.portal"
          }
        },
        "description": "One sampling assigned to the caller's lab (#73), with its full report (`LabReport`, null before one) and the lab's active server-held key for portal entries (`portal_key`, null when the lab holds none: portal entry is then refused 409)."
      },
      "ReportDetail": {
        "type": "object",
        "description": "A public mismatch report as staff triage sees it (Report) with the reported fruit's scan history (A8, #74). Scans are logged only by the web server's own render of the public fruit page (scans.py) and keep only a coarse place (country, region, city from the CDN's geolocation, any of them null when not forwarded) and a device class; there are no coordinates, and never an address or its hash. Times are Unix seconds.",
        "additionalProperties": false,
        "required": [
          "id",
          "fruit",
          "lot",
          "category",
          "note",
          "contact",
          "status",
          "outcome",
          "created_at",
          "resolved_at",
          "scans"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "fruit": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code",
              "public_id"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "public_id": {
                "type": "string"
              }
            }
          },
          "lot": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code",
              "public_id"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "public_id": {
                "type": "string"
              }
            }
          },
          "category": {
            "$ref": "#/components/schemas/ReportCategory"
          },
          "note": {
            "type": "string",
            "maxLength": 1000
          },
          "contact": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "resolved"
            ]
          },
          "outcome": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "confirmed",
              "unfounded",
              "duplicate",
              null
            ]
          },
          "created_at": {
            "type": "number"
          },
          "resolved_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "scans": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "total",
              "truncated",
              "items"
            ],
            "properties": {
              "total": {
                "type": "integer",
                "minimum": 0,
                "description": "Every scan of the fruit: its highest scan number (scans are numbered consecutively). Raw scan rows are deleted 90 days after the scan, but this count keeps them, so it can exceed the scans `items` lists."
              },
              "truncated": {
                "type": "boolean",
                "description": "More scans exist than `items` lists."
              },
              "items": {
                "type": "array",
                "maxItems": 50,
                "description": "The newest scans, newest first.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "scan_no",
                    "at",
                    "country",
                    "region",
                    "city",
                    "ua_class"
                  ],
                  "properties": {
                    "scan_no": {
                      "type": "integer",
                      "minimum": 1,
                      "description": "The scan's number for this fruit (1 is the first)."
                    },
                    "at": {
                      "type": "number",
                      "description": "Unix seconds."
                    },
                    "country": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "pattern": "^[A-Z0-9]{2}$",
                      "description": "ISO 3166-1 alpha-2 country the CDN located the visitor in."
                    },
                    "region": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "maxLength": 128
                    },
                    "city": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "maxLength": 128
                    },
                    "ua_class": {
                      "type": "string",
                      "enum": [
                        "mobile",
                        "desktop",
                        "other"
                      ],
                      "description": "The visitor's device class (crawlers and link previewers are never logged)."
                    }
                  }
                }
              }
            }
          }
        },
        "example": {
          "id": 12,
          "fruit": {
            "code": "Q-0928-014-0003",
            "public_id": "73879f17d0930440809333f141385eb6"
          },
          "lot": {
            "code": "LO-260928-014",
            "public_id": "5d0c7a3e9b1f4a2c8e6d0b4f7a9c3e1d"
          },
          "category": "scanned_many",
          "note": "Mã đã bị quét ở nhiều nơi.",
          "contact": "zalo 0901 234 567",
          "status": "open",
          "outcome": null,
          "created_at": 1790000000.5,
          "resolved_at": null,
          "scans": {
            "total": 4,
            "truncated": false,
            "items": [
              {
                "scan_no": 4,
                "at": 1789999000.0,
                "country": "VN",
                "region": "Hà Nội",
                "city": "Hà Nội",
                "ua_class": "mobile"
              },
              {
                "scan_no": 3,
                "at": 1789990000.0,
                "country": "VN",
                "region": "Gia Lai",
                "city": "Pleiku",
                "ua_class": "mobile"
              },
              {
                "scan_no": 2,
                "at": 1789980000.0,
                "country": "VN",
                "region": "Đắk Lắk",
                "city": null,
                "ua_class": "desktop"
              },
              {
                "scan_no": 1,
                "at": 1789970000.0,
                "country": "VN",
                "region": "Đắk Lắk",
                "city": "Buôn Ma Thuột",
                "ua_class": "other"
              }
            ]
          }
        }
      },
      "EpcisCaptureReport": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "capture_id",
          "events",
          "accepted",
          "duplicates",
          "rejected",
          "source",
          "tier",
          "results"
        ],
        "description": "The outcome of one capture, one result per event in document order.",
        "properties": {
          "capture_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The capture's id (the audit row's entity id)."
          },
          "events": {
            "type": "integer",
            "minimum": 0,
            "maximum": 500,
            "description": "Events in the document."
          },
          "accepted": {
            "type": "integer",
            "minimum": 0,
            "description": "Events stored by this capture."
          },
          "duplicates": {
            "type": "integer",
            "minimum": 0,
            "description": "Events already held with the same content."
          },
          "rejected": {
            "type": "integer",
            "minimum": 0,
            "description": "Events refused (nothing written for them)."
          },
          "source": {
            "type": "string",
            "enum": [
              "partner_capture"
            ],
            "description": "Provenance of captured events."
          },
          "tier": {
            "type": "string",
            "enum": [
              "self_declared"
            ],
            "description": "Trust tier of captured events (ADR 0001): always Self-declared."
          },
          "results": {
            "type": "array",
            "maxItems": 500,
            "items": {
              "$ref": "#/components/schemas/EpcisCaptureResult"
            }
          }
        }
      },
      "EpcisCaptureResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "index",
          "event_id",
          "status"
        ],
        "description": "One event's outcome. `step` and `references` only when accepted; `code` (and usually `detail`) only when rejected.",
        "properties": {
          "index": {
            "type": "integer",
            "minimum": 0,
            "description": "The event's position in eventList."
          },
          "event_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 512,
            "description": "The event's eventID; null when it sent none usable."
          },
          "status": {
            "type": "string",
            "enum": [
              "accepted",
              "duplicate",
              "rejected"
            ]
          },
          "step": {
            "type": "string",
            "enum": [
              "harvest",
              "receive",
              "pack",
              "ship",
              "observe"
            ],
            "description": "The journey step the event records: commissioning is the harvest, receiving, packing, shipping; sensor_reporting (#238) is an observation (`observe`).",
            "x-sdk-enum": [
              "harvest",
              "receive",
              "pack",
              "ship"
            ],
            "x-sdk-description": "The journey step the event records: commissioning is the harvest, receiving, packing, shipping."
          },
          "references": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "kind",
                "code"
              ],
              "properties": {
                "kind": {
                  "type": "string",
                  "enum": [
                    "lot",
                    "carton",
                    "shipment"
                  ],
                  "description": "The record kind."
                },
                "code": {
                  "type": "string",
                  "minLength": 1,
                  "maxLength": 40,
                  "description": "The record's code in the tenant."
                }
              }
            },
            "description": "The tenant's records the event names."
          },
          "code": {
            "type": "string",
            "enum": [
              "invalid_event",
              "unsupported_event_type",
              "missing_event_id",
              "unsupported_action",
              "unsupported_error_declaration",
              "unsupported_biz_step",
              "event_too_large",
              "event_too_deep",
              "event_id_conflict",
              "no_reference",
              "unknown_reference"
            ],
            "description": "Why the event was rejected."
          },
          "detail": {
            "type": "string",
            "maxLength": 300,
            "description": "The member or the identifier at fault (machine text, not translated)."
          }
        }
      },
      "CapturedEvent": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "event_id",
          "capture_id",
          "event_type",
          "biz_step",
          "step",
          "action",
          "event_time",
          "event_time_zone_offset",
          "read_point",
          "biz_location",
          "source",
          "tier",
          "captured_by",
          "captured_at",
          "references"
        ],
        "description": "An EPCIS event a partner captured: its statement, Self-declared.",
        "properties": {
          "event_id": {
            "type": "string",
            "maxLength": 512,
            "description": "The EPCIS eventID."
          },
          "capture_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The capture that stored it."
          },
          "event_type": {
            "type": "string",
            "enum": [
              "ObjectEvent",
              "AggregationEvent",
              "TransformationEvent"
            ]
          },
          "biz_step": {
            "type": "string",
            "enum": [
              "commissioning",
              "receiving",
              "packing",
              "shipping",
              "sensor_reporting"
            ],
            "description": "The CBV business step (bare term).",
            "x-sdk-enum": [
              "commissioning",
              "receiving",
              "packing",
              "shipping"
            ]
          },
          "step": {
            "type": "string",
            "enum": [
              "harvest",
              "receive",
              "pack",
              "ship",
              "observe"
            ],
            "description": "The journey step the event records: commissioning is the harvest, receiving, packing, shipping; sensor_reporting (#238) is an observation (`observe`).",
            "x-sdk-enum": [
              "harvest",
              "receive",
              "pack",
              "ship"
            ],
            "x-sdk-description": "The journey step the event records: commissioning is the harvest, receiving, packing, shipping."
          },
          "action": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "ADD",
              "OBSERVE",
              null
            ],
            "description": "The EPCIS action; null for a TransformationEvent."
          },
          "event_time": {
            "type": "string",
            "description": "eventTime as sent (RFC 3339)."
          },
          "event_time_zone_offset": {
            "type": "string",
            "pattern": "^[+-][0-9]{2}:[0-9]{2}$",
            "description": "eventTimeZoneOffset as sent."
          },
          "read_point": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 512,
            "description": "readPoint.id as sent."
          },
          "biz_location": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 512,
            "description": "bizLocation.id as sent."
          },
          "source": {
            "type": "string",
            "enum": [
              "partner_capture"
            ]
          },
          "tier": {
            "type": "string",
            "enum": [
              "self_declared"
            ]
          },
          "captured_by": {
            "type": "string",
            "description": "Opaque operator id of the capturing principal."
          },
          "captured_at": {
            "type": "number",
            "description": "Capture time, Unix seconds."
          },
          "references": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "kind",
                "code"
              ],
              "properties": {
                "kind": {
                  "type": "string",
                  "enum": [
                    "lot",
                    "carton",
                    "shipment"
                  ],
                  "description": "The record kind."
                },
                "code": {
                  "type": "string",
                  "minLength": 1,
                  "maxLength": 40,
                  "description": "The record's code in the tenant."
                }
              }
            },
            "description": "The tenant's records the event names."
          }
        }
      },
      "CapturedEventPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "items",
          "next_cursor"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "description": "The lot code."
          },
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/CapturedEvent"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Cursor of the next page; null on the last."
          }
        }
      },
      "BatchItemError": {
        "type": "object",
        "required": [
          "index",
          "status",
          "error",
          "code"
        ],
        "additionalProperties": false,
        "description": "One failed item of a batch request.",
        "properties": {
          "index": {
            "type": "integer",
            "minimum": 0,
            "description": "The item's position in the request (from 0)."
          },
          "status": {
            "type": "integer",
            "description": "The status the single-item route answers for this item."
          },
          "error": {
            "type": "string"
          },
          "code": {
            "type": "string"
          }
        },
        "example": {
          "index": 3,
          "status": 400,
          "error": "invalid kg: a number above 0 and at most 1000000",
          "code": "invalid_kg"
        }
      },
      "BatchCount": {
        "type": "object",
        "required": [
          "count"
        ],
        "additionalProperties": false,
        "properties": {
          "count": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000,
            "description": "How many records to create (at most 1,000)."
          }
        },
        "example": {
          "count": 200
        }
      },
      "FruitBatchItem": {
        "type": "object",
        "required": [
          "tenant",
          "code",
          "n",
          "public_id",
          "lot",
          "session",
          "line",
          "operator",
          "status",
          "labels_printed_at",
          "created_at",
          "updated_at",
          "qr_url",
          "label",
          "level",
          "level_pred",
          "maturity_class",
          "confidence",
          "model",
          "measured_at",
          "weight_kg",
          "level_sensory",
          "override",
          "pending_review",
          "grade",
          "eating_window",
          "record_tier",
          "knock_envelope_id",
          "scale_envelope_id",
          "override_envelope_id"
        ],
        "additionalProperties": false,
        "description": "A fruit allocated by a batch with its label payload; a batch issues no device command.",
        "properties": {
          "tenant": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "pattern": "^Q-[0-9]{3,}-[0-9]{4,}$",
            "description": "Fruit code `Q-<lot seq>-<n>`, unique within the tenant."
          },
          "n": {
            "type": "integer",
            "minimum": 1,
            "description": "Position of the fruit in its lot: 1, 2, ... without gaps."
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "128 random bits (hex); the public handle of the fruit, never derived from code or n."
          },
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "session": {
            "type": "string",
            "description": "Measurement session id."
          },
          "line": {
            "type": "string",
            "description": "The session's line."
          },
          "operator": {
            "type": [
              "string",
              "null"
            ],
            "description": "Opaque operator id `user-<id>` of the signed-in user who allocated it; null for API tokens."
          },
          "status": {
            "enum": [
              "awaiting_device",
              "recorded",
              "overridden",
              "rejected",
              "remeasured"
            ],
            "description": "Fruit record state; allocation starts at awaiting_device."
          },
          "labels_printed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds the label was printed (allocation)."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "qr_url": {
            "type": "string",
            "format": "uri",
            "description": "The QR content: a GS1 Digital Link `<base>/01/<gtin>/10/<lot>/21/<serial>` (20-character random serial) when the lot has a GTIN and a lot code of at most 20 characters, else `<base>/q/<public_id>`. The base is the deployment's resolver origin, AGRITRACE_RESOLVER_BASE (default https://txng.theio.vn).",
            "x-sdk-description": "The QR content: a GS1 Digital Link `<base>/01/<gtin>/10/<lot>/21/<serial>` (20-character random serial) when the lot has a GTIN and a lot code of at most 20 characters, else `<base>/q/<public_id>`. The base is https://txng.theio.vn until the permanent resolver domain is chosen."
          },
          "label": {
            "$ref": "#/components/schemas/FruitLabel"
          },
          "level": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "Effective ripeness level (1 Non, 2 Gia, 3 Chin toi, 4 Chin ruc): level_sensory while an override is bound, else level_pred."
          },
          "level_pred": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "The level the knocker sent (`produce.ripeness_level`); null when it sent none (a `mature` class is level 2 or 3 and is never guessed)."
          },
          "maturity_class": {
            "enum": [
              "immature",
              "mature",
              "overripe",
              "defect",
              "unknown",
              null
            ],
            "description": "The knocker's `produce.maturity_class`."
          },
          "confidence": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 1,
            "description": "Model confidence 0-1."
          },
          "model": {
            "type": [
              "string",
              "null"
            ],
            "description": "Model version that made the prediction."
          },
          "measured_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the knock (device event time)."
          },
          "weight_kg": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "description": "Net mass from the bound scale reading."
          },
          "level_sensory": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 4,
            "description": "The operator's sensory override (keys 1-4), if bound."
          },
          "override": {
            "type": "boolean",
            "description": "A sensory override is bound."
          },
          "pending_review": {
            "type": "boolean",
            "description": "Overlay: a bound envelope is quarantined and waits for review."
          },
          "grade": {
            "enum": [
              "A",
              "B",
              "reject",
              null
            ],
            "description": "Grade under the tenant's rules for the lot's variety (else the platform default), derived when the fruit was last bound or reviewed; null until a signed knock, a level and a weight are known (a defect or a reject level grades reject at once)."
          },
          "eating_window": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/EatingWindow"
              },
              {
                "type": "null"
              }
            ]
          },
          "record_tier": {
            "enum": [
              "self_declared",
              "device_recorded",
              "cross_checked",
              "lab_verified",
              null
            ],
            "description": "Trust tier of the fruit's own record, derived at read time; null until a knock is bound. Cross-checked needs the per-fruit volume quota, not reconciled yet."
          },
          "knock_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound knock envelope."
          },
          "scale_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound scale envelope."
          },
          "override_envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The bound sensory-override envelope."
          }
        },
        "example": {
          "tenant": "coop-dl",
          "code": "Q-014-0129",
          "n": 129,
          "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
          "lot": "LO-260928-014",
          "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
          "line": "A2",
          "operator": "user-7",
          "status": "awaiting_device",
          "labels_printed_at": 1790000000.5,
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5,
          "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
          "label": {
            "code": "Q-014-0129",
            "lot": "LO-260928-014",
            "n": 129,
            "line": "A2",
            "operator": "user-7",
            "printed_at": 1790000000.5,
            "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
          },
          "level": null,
          "level_pred": null,
          "maturity_class": null,
          "confidence": null,
          "model": null,
          "measured_at": null,
          "weight_kg": null,
          "level_sensory": null,
          "override": false,
          "pending_review": false,
          "grade": null,
          "eating_window": null,
          "record_tier": null,
          "knock_envelope_id": null,
          "scale_envelope_id": null,
          "override_envelope_id": null
        }
      },
      "FruitBatchResult": {
        "type": "object",
        "required": [
          "batch_id",
          "count",
          "items"
        ],
        "additionalProperties": false,
        "description": "The fruits a batch allocated, by n.",
        "properties": {
          "batch_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The stored batch request's id."
          },
          "count": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/FruitBatchItem"
            },
            "description": "In request order."
          }
        },
        "example": {
          "batch_id": 12,
          "count": 1,
          "items": [
            {
              "tenant": "coop-dl",
              "code": "Q-014-0129",
              "n": 129,
              "public_id": "5f0c9a1e7b2d4c3a8e6f1b0d9c7a2e4f",
              "lot": "LO-260928-014",
              "session": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
              "line": "A2",
              "operator": "user-7",
              "status": "awaiting_device",
              "labels_printed_at": 1790000000.5,
              "created_at": 1790000000.5,
              "updated_at": 1790000000.5,
              "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7",
              "label": {
                "code": "Q-014-0129",
                "lot": "LO-260928-014",
                "n": 129,
                "line": "A2",
                "operator": "user-7",
                "printed_at": 1790000000.5,
                "qr_url": "https://txng.theio.vn/01/00012345678905/10/LO-260928-014/21/k3Vd9_Qe2LmXa0Zr-Tb7"
              },
              "level": null,
              "level_pred": null,
              "maturity_class": null,
              "confidence": null,
              "model": null,
              "measured_at": null,
              "weight_kg": null,
              "level_sensory": null,
              "override": false,
              "pending_review": false,
              "grade": null,
              "eating_window": null,
              "record_tier": null,
              "knock_envelope_id": null,
              "scale_envelope_id": null,
              "override_envelope_id": null
            }
          ]
        }
      },
      "CartonBatchResult": {
        "type": "object",
        "required": [
          "batch_id",
          "count",
          "items"
        ],
        "additionalProperties": false,
        "description": "The cartons a batch created, by number.",
        "properties": {
          "batch_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The stored batch request's id."
          },
          "count": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/CartonDetail"
            },
            "description": "In request order."
          }
        },
        "example": {
          "batch_id": 12,
          "count": 1,
          "items": [
            {
              "tenant": "coop-dl",
              "code": "C-014-0017",
              "lot": "LO-260928-014",
              "carton_no": 17,
              "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
              "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
              "net_mass_kg": 8.53,
              "fruit_count": 3,
              "fruit_mass_kg": 8.89,
              "labels_printed_at": 1790000300.5,
              "created_by": "packer@coop.example",
              "created_at": 1790000300.5,
              "updated_at": 1790000310.0,
              "fruits": [
                "Q-014-0049",
                "Q-014-0050",
                "Q-014-0052"
              ]
            }
          ]
        }
      },
      "CartonContentsBatchResult": {
        "type": "object",
        "required": [
          "batch_id",
          "count",
          "items"
        ],
        "additionalProperties": false,
        "description": "The cartons as a batch left them, in request order.",
        "properties": {
          "batch_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The stored batch request's id."
          },
          "count": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/CartonDetail"
            },
            "description": "In request order."
          }
        },
        "example": {
          "batch_id": 12,
          "count": 1,
          "items": [
            {
              "tenant": "coop-dl",
              "code": "C-014-0017",
              "lot": "LO-260928-014",
              "carton_no": 17,
              "public_id": "8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
              "qr_url": "https://txng.theio.vn/q/8c1f0e2d9b7a4c3e8f6a1b2d3c4e5f60",
              "net_mass_kg": 6.1,
              "fruit_count": 2,
              "fruit_mass_kg": 6.0,
              "labels_printed_at": 1790000300.5,
              "created_by": "packer@coop.example",
              "created_at": 1790000300.5,
              "updated_at": 1790000310.0,
              "fruits": [
                "Q-014-0129",
                "Q-014-0130"
              ]
            }
          ]
        }
      },
      "HarvestBatchResult": {
        "type": "object",
        "required": [
          "batch_id",
          "count",
          "items"
        ],
        "additionalProperties": false,
        "description": "The declarations a batch stored, in request order.",
        "properties": {
          "batch_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The stored batch request's id."
          },
          "count": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/HarvestDeclaration"
            },
            "description": "In request order."
          }
        },
        "example": {
          "batch_id": 12,
          "count": 1,
          "items": [
            {
              "id": 7,
              "growing_area": "VN-TGOR-0387",
              "harvest_date": "2026-09-27",
              "season": "2026",
              "kg": 1820.0,
              "source": "self_declared",
              "declared_by": "admin@coop-dl",
              "declared_at": 1790500000.0
            }
          ]
        }
      },
      "GrowerBatchResult": {
        "type": "object",
        "required": [
          "batch_id",
          "count",
          "items"
        ],
        "additionalProperties": false,
        "description": "The growers a batch created, in request order.",
        "properties": {
          "batch_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The stored batch request's id."
          },
          "count": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/Grower"
            },
            "description": "In request order."
          }
        },
        "example": {
          "batch_id": 12,
          "count": 1,
          "items": [
            {
              "id": 12,
              "tenant": "coop-dl",
              "display_name": "Co-op member #12",
              "cooperative": "HTX Ngu Hiep",
              "public_consent": false,
              "consent_at": null,
              "consent_date": null,
              "consent_scope": null,
              "created_at": 1790000000.5,
              "updated_at": 1790000000.5,
              "name": "Nguyen Van An"
            }
          ]
        }
      },
      "CartonContentsBatchItem": {
        "type": "object",
        "required": [
          "carton",
          "fruits",
          "net_mass_kg"
        ],
        "additionalProperties": false,
        "description": "One carton's new contents, replacing its previous ones.",
        "properties": {
          "carton": {
            "type": "string",
            "pattern": "^C-[0-9]{3,19}-[0-9]{4}$",
            "description": "A carton of the path's lot; at most once per batch."
          },
          "fruits": {
            "type": "array",
            "minItems": 1,
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^Q-[0-9]{3,19}-[0-9]{4,19}$"
            },
            "description": "Codes of packable fruits of the carton's lot (status recorded or overridden, grade A or B), each in no other carton."
          },
          "net_mass_kg": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1000,
            "description": "The carton's weighed net mass."
          }
        }
      },
      "HarvestBatchItem": {
        "type": "object",
        "required": [
          "growing_area",
          "harvest_date",
          "kg"
        ],
        "additionalProperties": false,
        "properties": {
          "growing_area": {
            "type": "string",
            "pattern": "^[A-Z]{2}(?:-[A-Z0-9]{1,12}){1,4}$",
            "description": "Code of a growing area the caller may write."
          },
          "harvest_date": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The harvest date; not later than today."
          },
          "kg": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1000000,
            "description": "Mass harvested on that date."
          }
        },
        "description": "One declaration; an area and date at most once per batch."
      },
      "CartonContentsBatch": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "description": "Up to 1,000 cartons of the lot, applied in order.",
        "properties": {
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/CartonContentsBatchItem"
            }
          }
        },
        "example": {
          "items": [
            {
              "carton": "C-014-0017",
              "fruits": [
                "Q-014-0129",
                "Q-014-0130"
              ],
              "net_mass_kg": 6.1
            }
          ]
        }
      },
      "HarvestBatch": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "description": "Up to 1,000 harvest declarations across the tenant's areas.",
        "properties": {
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/HarvestBatchItem"
            }
          }
        },
        "example": {
          "items": [
            {
              "growing_area": "VN-DL-SR-0123",
              "harvest_date": "2026-09-27",
              "kg": 1820
            }
          ]
        }
      },
      "GrowerBatch": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "description": "Up to 1,000 growers.",
        "properties": {
          "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "$ref": "#/components/schemas/GrowerCreate"
            }
          }
        },
        "example": {
          "items": [
            {
              "name": "Nguyễn Văn A",
              "cooperative": "HTX Đắk Lắk"
            }
          ]
        }
      },
      "RecordsExportRow": {
        "description": "One row of a records-request export (W1-3, #152): every column on every row, an empty cell an empty string. Each property documents which row kinds fill it, its unit and its format.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "record_type",
          "traceability_lot_code",
          "critical_tracking_event",
          "event_date",
          "event_time",
          "record_source",
          "event_id",
          "location",
          "location_description",
          "location_address",
          "location_registration",
          "product_description",
          "quantity",
          "unit_of_measure",
          "area_declared_kg",
          "carton",
          "fruit_count",
          "supplier_name",
          "supplier_organisation",
          "supplier_code",
          "supplier_address",
          "supplier_registration",
          "harvest_date",
          "shipment",
          "container",
          "seal_number",
          "destination",
          "border_gate",
          "consignee_name",
          "consignee_address",
          "consignee_country",
          "consignee_gln",
          "consignee_gacc_record",
          "reference_document_type",
          "reference_document_number",
          "lab_key_custody",
          "lab_market",
          "sample",
          "analyte",
          "result_outcome",
          "result_value",
          "result_unit",
          "limit_kind",
          "limit_value",
          "limit_source",
          "verdict",
          "sealed_digest",
          "sealed_basis",
          "recall_kind",
          "recall_reason",
          "recall_scope",
          "hold_kind",
          "hold_status",
          "device_events_truncated"
        ],
        "properties": {
          "record_type": {
            "type": "string",
            "enum": [
              "cte",
              "transformation_input",
              "sealed_record",
              "lab_result",
              "recall",
              "hold"
            ],
            "description": "The row kind: cte (a critical tracking event), transformation_input (#91: a lot a merge consumed, with the kg taken from it; its critical_tracking_event is transformation), sealed_record (the registry facts frozen at the pack event), lab_result (one result of the lot's signed lab report), recall, or hold (an open or escalated hold of the lot, at its opening time). The CSV also starts, when a lot's signed device events were cut, with a truncation_notice row per cut lot; a JSON row never has that kind.",
            "x-sdk-enum": [
              "cte",
              "sealed_record",
              "lab_result",
              "recall",
              "hold"
            ],
            "x-sdk-description": "The row kind: cte (a critical tracking event), sealed_record (the registry facts frozen at the pack event), lab_result (one result of the lot's signed lab report), recall, or hold (an open or escalated hold of the lot, at its opening time). The CSV also starts, when a lot's signed device events were cut, with a truncation_notice row per cut lot; a JSON row never has that kind."
          },
          "traceability_lot_code": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$",
            "description": "The lot code (the traceability lot code of every row)."
          },
          "critical_tracking_event": {
            "type": "string",
            "enum": [
              "harvesting",
              "receiving",
              "cooling",
              "transformation",
              "initial_packing",
              "shipping",
              ""
            ],
            "description": "The critical tracking event of a cte row: harvesting (at the growing area), receiving and cooling (signed device events at their facility), initial_packing (one per carton at the lot's facility, and a device's signed pack event at its facility) or shipping (one per carton on the departed shipment, at the departure facility, and a device's signed ship event at its facility), or transformation (#91: a lot merge, on the cte row of the lot it produced and on each transformation_input row, at the merge's facility and time, all with the merge's event_id); empty for the other row kinds.",
            "x-sdk-enum": [
              "harvesting",
              "receiving",
              "cooling",
              "initial_packing",
              "shipping",
              ""
            ],
            "x-sdk-description": "The critical tracking event of a cte row: harvesting (at the growing area), receiving and cooling (signed device events at their facility), initial_packing (one per carton at the lot's facility, and a device's signed pack event at its facility) or shipping (one per carton on the departed shipment, at the departure facility, and a device's signed ship event at its facility); empty for the other row kinds."
          },
          "event_date": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The row's local date (Asia/Ho_Chi_Minh), YYYY-MM-DD: the event, the pack time (sealed_record), the report's signing time (lab_result) or the recall time."
          },
          "event_time": {
            "type": "string",
            "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]\\+07:00$|^$",
            "description": "The local time with its offset, whole seconds, hh:mm:ss+07:00; empty for a harvest known only by its date."
          },
          "record_source": {
            "type": "string",
            "enum": [
              "signed_device_event",
              "self_declared",
              "system_record",
              "sealed_record",
              "signed_lab_report",
              ""
            ],
            "description": "How the row's fact was recorded: signed_device_event (a signed device or harvest event), self_declared (the growing area's harvest declaration), system_record (the per-carton packing and shipping records, recall), sealed_record or signed_lab_report; empty for a harvest date without any record. A staff label, not a public trust tier."
          },
          "event_id": {
            "type": "string",
            "maxLength": 128,
            "description": "The signed event's envelope id (harvesting from a signed event, receiving, cooling, and a device's signed packing or shipping event); the merge's id on a transformation row (#91); empty otherwise.",
            "x-sdk-description": "The signed event's envelope id (harvesting from a signed event, receiving, cooling, and a device's signed packing or shipping event); empty otherwise."
          },
          "location": {
            "type": "string",
            "maxLength": 64,
            "description": "Where: the growing area code (harvesting), the facility code (receiving, cooling, packing, shipping, sealed_record) or the lab code (lab_result); empty for the recall row or an unknown place."
          },
          "location_description": {
            "type": "string",
            "description": "The growing area's commune, district and province, the facility's name or the lab's name; empty when unknown. #273: a growing area coded by official administrative unit codes has its commune and province instead (Viet Nam has had no district level since 2025-07-01).",
            "x-sdk-description": "The growing area's commune, district and province, the facility's name or the lab's name; empty when unknown."
          },
          "location_address": {
            "type": "string",
            "description": "The facility's address, district and province, or the growing area's commune, district and province, comma-separated; empty when unknown. #273: a facility or growing area coded by official administrative unit codes has its commune and province instead (Viet Nam has had no district level since 2025-07-01).",
            "x-sdk-description": "The facility's address, district and province, or the growing area's commune, district and province, comma-separated; empty when unknown."
          },
          "location_registration": {
            "type": "string",
            "description": "The GACC packing-house (PHC) code of the facility or growing-area (PUC) code of the area, as the tenant's registry records it; empty when none."
          },
          "product_description": {
            "type": "string",
            "description": "The lot's product and variety, space-separated (e.g. `durian Ri6`)."
          },
          "quantity": {
            "description": "The quantity in kilograms (unit_of_measure kg), at most 3 decimals: the lot's signed harvest mass (never an area's declaration, see area_declared_kg), the mass a signed device event carries (receiving, cooling, packing, shipping), a carton's net mass, the sealed lot's net mass, or a merge's kilograms (#91: taken from an input, or of the output); empty without one.",
            "oneOf": [
              {
                "type": "number",
                "minimum": 0
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ],
            "x-sdk-description": "The quantity in kilograms (unit_of_measure kg), at most 3 decimals: the lot's signed harvest mass (never an area's declaration, see area_declared_kg), the mass a signed device event carries (receiving, cooling, packing, shipping), a carton's net mass or the sealed lot's net mass; empty without one."
          },
          "unit_of_measure": {
            "type": "string",
            "enum": [
              "kg",
              ""
            ],
            "description": "`kg` when quantity is given, else empty."
          },
          "area_declared_kg": {
            "description": "Harvesting row without a signed harvest mass only: the growing area's self-declared harvest in kilograms for the harvest date (the area's harvest declaration). It is the AREA's figure for the day, shared by every lot of that area and day, not this lot's mass: never add it across lots. Empty on every other row.",
            "oneOf": [
              {
                "type": "number",
                "exclusiveMinimum": 0
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          },
          "carton": {
            "type": "string",
            "pattern": "^C-[0-9]{3,19}-[0-9]{4}$|^$",
            "description": "The carton code (initial_packing, shipping); empty otherwise."
          },
          "fruit_count": {
            "description": "The fruits in the carton (initial_packing, shipping) or in the sealed lot (sealed_record); empty otherwise.",
            "oneOf": [
              {
                "type": "integer",
                "minimum": 0
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          },
          "supplier_name": {
            "type": "string",
            "description": "One step back (Circular 17/2021 Art. 6 supplier): the grower of the lot's growing area, a grower of the lot's own tenant only, as its member label (`Co-op member #<id>`); empty when none. Never the grower's legal name, for any role or consent: the name may appear only for an allowed role whose grower's recorded consent scope covers traceability or authority disclosure, and no such scope value is defined yet (#152)."
          },
          "supplier_organisation": {
            "type": "string",
            "description": "The grower's cooperative; empty when none."
          },
          "supplier_code": {
            "type": "string",
            "maxLength": 64,
            "description": "The growing area code (the sealed record's frozen code on its row); empty without an area."
          },
          "supplier_address": {
            "type": "string",
            "description": "The growing area's commune, district and province, comma-separated; empty when unknown. #273: a growing area coded by official administrative unit codes has its commune and province instead (Viet Nam has had no district level since 2025-07-01).",
            "x-sdk-description": "The growing area's commune, district and province, comma-separated; empty when unknown."
          },
          "supplier_registration": {
            "type": "string",
            "description": "The growing area's GACC growing-area (PUC) code; empty when none."
          },
          "harvest_date": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$|^$",
            "description": "The lot's harvest date, YYYY-MM-DD; empty when not recorded."
          },
          "shipment": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$|^$",
            "description": "One step forward: the shipment code (shipping); empty otherwise."
          },
          "container": {
            "type": "string",
            "pattern": "^[A-Z]{3}[UJZ][0-9]{7}$|^$",
            "description": "The ISO 6346 container number (shipping); empty otherwise."
          },
          "seal_number": {
            "type": "string",
            "maxLength": 64,
            "description": "The lot's seal number on the shipment (shipping); empty otherwise."
          },
          "destination": {
            "type": "string",
            "pattern": "^[A-Z]{2}$|^$",
            "description": "The destination market, ISO 3166-1 alpha-2 (shipping); empty otherwise."
          },
          "border_gate": {
            "type": "string",
            "maxLength": 100,
            "description": "The border gate the shipment heads for (shipping); empty otherwise."
          },
          "consignee_name": {
            "type": "string",
            "description": "The shipment's consignee (immediate subsequent recipient); empty until the shipment records one (#153)."
          },
          "consignee_address": {
            "type": "string",
            "description": "The consignee's address; empty until recorded (#153)."
          },
          "consignee_country": {
            "type": "string",
            "pattern": "^[A-Z]{2}$|^$",
            "description": "The consignee's country, ISO 3166-1 alpha-2; empty until recorded (#153)."
          },
          "consignee_gln": {
            "type": "string",
            "pattern": "^[0-9]{13}$|^$",
            "description": "The consignee's GS1 GLN; empty until recorded (#153)."
          },
          "consignee_gacc_record": {
            "type": "string",
            "description": "The importer's GACC registration number; empty until recorded (#153)."
          },
          "reference_document_type": {
            "type": "string",
            "enum": [
              "test_report",
              "phytosanitary_certificate",
              "certificate_of_origin",
              "commercial_invoice",
              "packing_list",
              ""
            ],
            "description": "The reference document's type: test_report on a lab_result row (the shipment's documents once #153 records them); empty otherwise."
          },
          "reference_document_number": {
            "type": "string",
            "maxLength": 64,
            "description": "The reference document's number: the lab's report number on a lab_result row; empty otherwise."
          },
          "lab_key_custody": {
            "type": "string",
            "enum": [
              "lab",
              "server",
              ""
            ],
            "description": "Who holds the key that signed the lab report: lab (uploaded) or server (portal entry); empty on other rows."
          },
          "lab_market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$|^$",
            "description": "The market whose limits judged the report, ISO 3166-1 alpha-2; empty on other rows."
          },
          "sample": {
            "description": "The sample number k (lab_result); empty otherwise.",
            "oneOf": [
              {
                "type": "integer",
                "minimum": 1
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          },
          "analyte": {
            "type": "string",
            "maxLength": 64,
            "description": "The analyte (lab_result), e.g. cadmium, auramine_o; empty otherwise."
          },
          "result_outcome": {
            "type": "string",
            "enum": [
              "measured",
              "not_detected",
              ""
            ],
            "description": "measured or not_detected (lab_result); empty otherwise."
          },
          "result_value": {
            "description": "The measured value in result_unit (lab_result, measured); empty otherwise.",
            "oneOf": [
              {
                "type": "number"
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          },
          "result_unit": {
            "type": "string",
            "maxLength": 32,
            "description": "The unit the lab signed (lab_result), e.g. mg/kg; empty otherwise."
          },
          "limit_kind": {
            "type": "string",
            "enum": [
              "max",
              "banned",
              ""
            ],
            "description": "The market limit that judged the result: max or banned; empty when the market sets none or on other rows."
          },
          "limit_value": {
            "description": "The maximum in result_unit (limit_kind max); empty otherwise.",
            "oneOf": [
              {
                "type": "number",
                "minimum": 0
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          },
          "limit_source": {
            "type": "string",
            "description": "The source of the limit as it stood when the report was judged; empty when none."
          },
          "verdict": {
            "type": "string",
            "enum": [
              "pass",
              "fail",
              ""
            ],
            "description": "pass or fail (lab_result); empty otherwise."
          },
          "sealed_digest": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$|^$",
            "description": "The SHA-256 (lower-case hex) of the sealed record (sealed_record); empty otherwise."
          },
          "sealed_basis": {
            "type": "string",
            "enum": [
              "transition",
              "migration",
              ""
            ],
            "description": "How the sealed record was taken: transition (inside the pack transaction) or migration; empty otherwise."
          },
          "recall_kind": {
            "type": "string",
            "enum": [
              "recall",
              "withdrawal",
              ""
            ],
            "description": "recall or withdrawal (recall row); empty otherwise."
          },
          "recall_reason": {
            "description": "The recall's reason category (recall row); empty otherwise.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/RecallReason"
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          },
          "recall_scope": {
            "type": "string",
            "enum": [
              "consumer",
              "retail",
              "wholesale",
              ""
            ],
            "description": "The recall depth: consumer, retail or wholesale (recall row); empty otherwise."
          },
          "hold_kind": {
            "type": "string",
            "enum": [
              "report",
              "quarantine",
              "key_compromise",
              "lab_failure",
              "rejected_component",
              ""
            ],
            "description": "The hold's kind (hold row): an open public report, a quarantined component, a device key revoked for compromise, a failing lab result or a rejected component; empty otherwise. ADR 0001: a hold caps what the lot's evidence shows (a compromised key caps it at Self-declared), so read the lot's signed rows with its holds."
          },
          "hold_status": {
            "type": "string",
            "enum": [
              "open",
              "escalated",
              ""
            ],
            "description": "The hold's status (hold row): open or escalated (still unresolved); empty otherwise. Resolved and withdrawn holds are not listed."
          },
          "device_events_truncated": {
            "type": "string",
            "enum": [
              "true",
              "false"
            ],
            "description": "On every row: \"true\" when this row's lot has more than 1,000 signed device events (receiving, cooling, packing, shipping) and the sheet lists only the first 1,000, else \"false\". The CSV carries it, and starts with a truncation_notice row per cut lot, so a forwarded file still says it is incomplete; the document's `truncated` says the same for the whole document."
          }
        }
      },
      "FsmaRow": {
        "description": "One row of the FSMA 204 sortable spreadsheet (GET /v1/fsma.csv, GET /v1/lots/{lot}/fsma.csv; #158): every column on every row, in this order, an empty cell an empty string. One row per critical tracking event, sorted by time. The key data elements of 21 CFR 1 Subpart S, checked column by column against FDA's sortable spreadsheet template.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "traceability_lot_code",
          "critical_tracking_event",
          "event_date",
          "event_time",
          "location",
          "quantity",
          "unit_of_measure",
          "growing_area",
          "parcel",
          "producer",
          "device_id",
          "event_id",
          "commodity",
          "variety",
          "field_name",
          "traceability_lot_code_source",
          "traceability_lot_code_source_reference",
          "shipper_location_name",
          "shipper_location_address",
          "shipper_location_gln",
          "recipient_location_name",
          "recipient_location_address",
          "recipient_location_gln",
          "reference_document_type",
          "reference_document_number",
          "container",
          "input_traceability_lot_code",
          "input_quantity"
        ],
        "properties": {
          "traceability_lot_code": {
            "type": "string",
            "description": "The traceability lot code: the lot's code. On a transformation row, the NEW lot's code (the lot the merge produced, #91)."
          },
          "critical_tracking_event": {
            "type": "string",
            "enum": [
              "harvesting",
              "receiving",
              "cooling",
              "initial_packing",
              "shipping",
              "transformation"
            ],
            "description": "The FSMA 204 critical tracking event: harvesting, receiving, cooling and initial_packing from a signed device event (/developers/downloads/event-types-v1.json), shipping from a signed device event or a departed shipment, transformation from a lot merge (#91)."
          },
          "event_date": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The event's date, YYYY-MM-DD: in the offset the device signed for a device event, in Asia/Ho_Chi_Minh (+07:00) for a departure or a merge."
          },
          "event_time": {
            "type": "string",
            "pattern": "^[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}$",
            "description": "The event's time with its offset, whole seconds, hh:mm:ss+hh:mm (the same offset as event_date)."
          },
          "location": {
            "type": "string",
            "description": "The code of the facility (or growing area) where the event happened: the device event's facility, the shipment's departure facility, the merge's facility."
          },
          "quantity": {
            "description": "The quantity: the mass.net reading of a device event, the kilograms of the lot's cartons on a departed shipment, or the kilograms the merge produced (transformation); empty without one.",
            "oneOf": [
              {
                "type": "number"
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          },
          "unit_of_measure": {
            "type": "string",
            "description": "The quantity's unit: the reading's unit for a device event, kg for a departure or a merge; empty without a quantity."
          },
          "growing_area": {
            "type": "string",
            "description": "The growing area code: the device event's, or the lot's for a departure or a merge; empty without one."
          },
          "parcel": {
            "type": "string",
            "description": "The parcel the device event names; empty otherwise."
          },
          "producer": {
            "type": "string",
            "description": "The producer the device event names; empty otherwise."
          },
          "device_id": {
            "type": "string",
            "description": "The id of the device that signed the event; empty on a row the platform recorded (a departure, a merge)."
          },
          "event_id": {
            "type": "string",
            "description": "The signed device event's envelope id, or the merge's event id on a transformation row (the eventID of its EPCIS TransformationEvent without urn:uuid:); empty on a departure."
          },
          "commodity": {
            "type": "string",
            "description": "The lot's product (for example durian); empty when the lot code is not one of the company's lots."
          },
          "variety": {
            "type": "string",
            "description": "The lot's variety (for example Ri6); empty without one."
          },
          "field_name": {
            "type": "string",
            "description": "The name the grower uses for the row's growing area (FSMA 204: the name of the field or other growing area the food was harvested from); empty when the area has no name. The area's code is in growing_area."
          },
          "traceability_lot_code_source": {
            "type": "string",
            "description": "Where the traceability lot code was assigned: the lot's facility, its name and address (street, district, province); empty when the lot code is not one of the company's lots. #273: a facility coded by official administrative unit codes has its commune and province instead (Viet Nam has had no district level since 2025-07-01).",
            "x-sdk-description": "Where the traceability lot code was assigned: the lot's facility, its name and address (street, district, province); empty when the lot code is not one of the company's lots."
          },
          "traceability_lot_code_source_reference": {
            "type": "string",
            "pattern": "^[0-9]{13}$|^$",
            "description": "The GS1 GLN of that facility (#161), a reference that may be given instead of the location description; empty without a GLN."
          },
          "shipper_location_name": {
            "type": "string",
            "description": "Where the food came from. Shipping: the name of the facility it was shipped from. Receiving: the growing area's name (the farm it came from). Empty on other rows."
          },
          "shipper_location_address": {
            "type": "string",
            "description": "That location's address: the facility's street, district and province, or the growing area's commune, district and province. #273: a facility or growing area coded by official administrative unit codes has its commune and province instead (Viet Nam has had no district level since 2025-07-01).",
            "x-sdk-description": "That location's address: the facility's street, district and province, or the growing area's commune, district and province."
          },
          "shipper_location_gln": {
            "type": "string",
            "pattern": "^[0-9]{13}$|^$",
            "description": "That location's GS1 GLN (#161); empty without one."
          },
          "recipient_location_name": {
            "type": "string",
            "description": "Where the food went. Shipping from a departed shipment: the consignee's legal name (the immediate subsequent recipient, #153). Receiving: the name of the facility that received it. Empty on other rows."
          },
          "recipient_location_address": {
            "type": "string",
            "description": "That location's address: the consignee's postal address and country (ISO 3166-1 alpha-2), or the facility's street, district and province. #273: a facility coded by official administrative unit codes has its commune and province instead (Viet Nam has had no district level since 2025-07-01).",
            "x-sdk-description": "That location's address: the consignee's postal address and country (ISO 3166-1 alpha-2), or the facility's street, district and province."
          },
          "recipient_location_gln": {
            "type": "string",
            "pattern": "^[0-9]{13}$|^$",
            "description": "That location's GS1 GLN: the consignee's (#153) or the facility's (#161); empty without one."
          },
          "reference_document_type": {
            "type": "string",
            "description": "The types of the departed shipment's documents (#153: phytosanitary_certificate, certificate_of_origin, commercial_invoice, packing_list, customs_declaration, bill_of_lading, air_waybill, test_report, other), sorted, separated by \"; \"; empty on other rows."
          },
          "reference_document_number": {
            "type": "string",
            "description": "The numbers of those documents, in the same order, separated by \"; \"."
          },
          "container": {
            "type": "string",
            "pattern": "^[A-Z]{3}[UJZ][0-9]{7}$|^$",
            "description": "The ISO 6346 container number of the departed shipment; empty otherwise."
          },
          "input_traceability_lot_code": {
            "type": "string",
            "description": "Transformation row: the code of the lot the merge used (one row per lot used); empty on other rows."
          },
          "input_quantity": {
            "description": "Transformation row: the kilograms the merge took from that lot (unit_of_measure kg); empty on other rows.",
            "oneOf": [
              {
                "type": "number",
                "minimum": 0
              },
              {
                "type": "string",
                "enum": [
                  ""
                ]
              }
            ]
          }
        },
        "x-not-in-sdk": true
      },
      "RecordsExport": {
        "description": "The records-request export of one lot (W1-3, #152): one sortable sheet for an authority (Circular 17/2021 Art. 6: one step back, one step forward) or a buyer (FSMA 204's electronic sortable spreadsheet within 24 hours). Rows in time order: the critical tracking events (harvesting, receiving, cooling, initial_packing per carton, shipping per carton), the sealed record, every lab result, the recall when any, and every open or escalated hold of the lot. Times are local (+07:00). Bounded: at most 1,000 signed device events (receiving, cooling, packing, shipping) (`truncated` when more exist), 9,999 cartons and 384 lab results.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "format",
          "lot",
          "status",
          "generated_at",
          "truncated",
          "sealed_record",
          "columns",
          "rows"
        ],
        "properties": {
          "format": {
            "type": "string",
            "const": "agritrace-records-export/1"
          },
          "lot": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$"
          },
          "status": {
            "type": "string",
            "enum": [
              "draft",
              "open",
              "paused",
              "closed",
              "packed",
              "shipped",
              "recalled",
              "withdrawn"
            ],
            "description": "The lot's status when the export was taken."
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          },
          "truncated": {
            "type": "boolean",
            "description": "True when the lot has more than 1,000 signed device events (receiving, cooling, packing, shipping) and only the first 1,000 are listed."
          },
          "sealed_record": {
            "description": "The registry facts frozen at the pack event (sealed_lot.py) with their seal digest and basis; null while the lot is not packed.",
            "oneOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "facts",
                  "digest",
                  "basis"
                ],
                "properties": {
                  "facts": {
                    "type": "object",
                    "description": "The sealed facts as frozen (lot, cartons, growing_area, packing_house, durian_protocol). A lot packed since addresses are coded by official administrative unit codes (#273), with its packing house or growing area coded, also has admin_units_version, and its growing_area and packing_house name the commune and province with their official codes instead of the district, as the customs dossier's format 2 does.",
                    "x-sdk-description": "The sealed facts as frozen (lot, cartons, growing_area, packing_house, durian_protocol)."
                  },
                  "digest": {
                    "type": "string",
                    "pattern": "^[0-9a-f]{64}$"
                  },
                  "basis": {
                    "type": "string",
                    "enum": [
                      "transition",
                      "migration"
                    ]
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          },
          "columns": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "record_type",
                "traceability_lot_code",
                "critical_tracking_event",
                "event_date",
                "event_time",
                "record_source",
                "event_id",
                "location",
                "location_description",
                "location_address",
                "location_registration",
                "product_description",
                "quantity",
                "unit_of_measure",
                "area_declared_kg",
                "carton",
                "fruit_count",
                "supplier_name",
                "supplier_organisation",
                "supplier_code",
                "supplier_address",
                "supplier_registration",
                "harvest_date",
                "shipment",
                "container",
                "seal_number",
                "destination",
                "border_gate",
                "consignee_name",
                "consignee_address",
                "consignee_country",
                "consignee_gln",
                "consignee_gacc_record",
                "reference_document_type",
                "reference_document_number",
                "lab_key_custody",
                "lab_market",
                "sample",
                "analyte",
                "result_outcome",
                "result_value",
                "result_unit",
                "limit_kind",
                "limit_value",
                "limit_source",
                "verdict",
                "sealed_digest",
                "sealed_basis",
                "recall_kind",
                "recall_reason",
                "recall_scope",
                "hold_kind",
                "hold_status",
                "device_events_truncated"
              ]
            },
            "description": "The column names in order (the CSV header): every RecordsExportRow property."
          },
          "rows": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/RecordsExportRow"
            }
          }
        }
      },
      "RecordsExportRange": {
        "description": "One page of the records-request export of the tenant's lots created in [start, end) (W1-3, #152): the rows of each lot of the page, lot by lot in creation order, as RecordsExport lists them. A page holds at most 50 lots whose cartons together stay within 9,999 (always at least one lot); `next_cursor` names the next page.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "format",
          "start",
          "end",
          "generated_at",
          "lots",
          "next_cursor",
          "truncated",
          "columns",
          "rows"
        ],
        "properties": {
          "format": {
            "type": "string",
            "const": "agritrace-records-export-range/1"
          },
          "start": {
            "type": "string",
            "format": "date-time"
          },
          "end": {
            "type": "string",
            "format": "date-time"
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          },
          "lots": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "type": "string",
              "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$"
            },
            "description": "The lot codes of this page, in creation order."
          },
          "next_cursor": {
            "description": "The `cursor` of the next page; null on the last page.",
            "oneOf": [
              {
                "type": "string",
                "pattern": "^[0-9]{1,18}$"
              },
              {
                "type": "null"
              }
            ]
          },
          "truncated": {
            "type": "boolean",
            "description": "True when a lot of the page had more than 1,000 signed device events (receiving, cooling, packing, shipping)."
          },
          "columns": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "record_type",
                "traceability_lot_code",
                "critical_tracking_event",
                "event_date",
                "event_time",
                "record_source",
                "event_id",
                "location",
                "location_description",
                "location_address",
                "location_registration",
                "product_description",
                "quantity",
                "unit_of_measure",
                "area_declared_kg",
                "carton",
                "fruit_count",
                "supplier_name",
                "supplier_organisation",
                "supplier_code",
                "supplier_address",
                "supplier_registration",
                "harvest_date",
                "shipment",
                "container",
                "seal_number",
                "destination",
                "border_gate",
                "consignee_name",
                "consignee_address",
                "consignee_country",
                "consignee_gln",
                "consignee_gacc_record",
                "reference_document_type",
                "reference_document_number",
                "lab_key_custody",
                "lab_market",
                "sample",
                "analyte",
                "result_outcome",
                "result_value",
                "result_unit",
                "limit_kind",
                "limit_value",
                "limit_source",
                "verdict",
                "sealed_digest",
                "sealed_basis",
                "recall_kind",
                "recall_reason",
                "recall_scope",
                "hold_kind",
                "hold_status",
                "device_events_truncated"
              ]
            },
            "description": "The column names in order (the CSV header): every RecordsExportRow property."
          },
          "rows": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/RecordsExportRow"
            }
          }
        }
      },
      "RegistryList": {
        "type": "object",
        "description": "An imported published PUC/PHC code list (#150). On the import's answer, `superseded` names the list it replaced (null for the first of its kind, market and crop).",
        "additionalProperties": false,
        "required": [
          "id",
          "kind",
          "market",
          "crop",
          "source_url",
          "source_sha256",
          "source_media_type",
          "published_on",
          "file_name",
          "file_sha256",
          "file_size",
          "entry_count",
          "imported_at",
          "imported_by",
          "superseded_by",
          "superseded_at",
          "retired_by",
          "retire_reason",
          "current",
          "stale"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "kind": {
            "type": "string",
            "enum": [
              "puc",
              "phc"
            ],
            "description": "puc: growing-area codes; phc: packing-house codes."
          },
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "The destination market whose protocol the codes are registered for (ISO 3166-1 alpha-2)."
          },
          "crop": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$",
            "description": "One of the platform's crops (AGRITRACE_REGISTRY_CROPS; by default coconut, dragon_fruit, durian, jackfruit, mango)."
          },
          "source_url": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "The page the list was downloaded from."
          },
          "source_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the file the authority published (its spreadsheet or PDF), which the admin converted into the stored CSV. The server computed it when the original was uploaded (PUT /v1/registry-sources/{sha256}); it ties a Cross-checked registration step back to the authority's own file."
          },
          "source_media_type": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "application/pdf",
              "application/vnd.ms-excel",
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              "text/csv",
              null
            ],
            "description": "The media type of the authority's original file `source_sha256` names (GET /v1/registry-lists/{id}/source)."
          },
          "published_on": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The date the authority published the list, when known."
          },
          "file_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "file_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the stored file."
          },
          "file_size": {
            "type": "integer",
            "minimum": 1
          },
          "entry_count": {
            "type": "integer",
            "minimum": 0
          },
          "imported_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "imported_by": {
            "type": "string"
          },
          "superseded_by": {
            "type": [
              "integer",
              "null"
            ]
          },
          "superseded_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When a later import superseded the list, or when it was retired (then `superseded_by` is null)."
          },
          "retired_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who retired the list (POST /v1/registry-lists/{id}/retire); null unless retired."
          },
          "retire_reason": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200,
            "description": "Why the list was retired; null unless retired."
          },
          "current": {
            "type": "boolean",
            "description": "Neither superseded by a later import nor retired."
          },
          "stale": {
            "type": "boolean",
            "description": "Current and older than the configured age."
          },
          "superseded": {
            "type": [
              "integer",
              "null"
            ],
            "description": "Only on the import's answer: the id of the list this import superseded."
          }
        },
        "example": {
          "id": 3,
          "kind": "puc",
          "market": "CN",
          "crop": "durian",
          "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
          "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
          "source_media_type": "application/pdf",
          "published_on": "2026-09-25",
          "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
          "file_sha256": "9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f",
          "file_size": 48213,
          "entry_count": 812,
          "imported_at": 1790000000.5,
          "imported_by": "admin@croppath.example",
          "superseded_by": null,
          "superseded_at": null,
          "retired_by": null,
          "retire_reason": null,
          "current": true,
          "stale": false,
          "superseded": 2
        }
      },
      "RegistryListDetail": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "kind",
          "market",
          "crop",
          "source_url",
          "source_sha256",
          "source_media_type",
          "published_on",
          "file_name",
          "file_sha256",
          "file_size",
          "entry_count",
          "imported_at",
          "imported_by",
          "superseded_by",
          "superseded_at",
          "retired_by",
          "retire_reason",
          "current",
          "stale",
          "status_counts",
          "max_age_days"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "kind": {
            "type": "string",
            "enum": [
              "puc",
              "phc"
            ],
            "description": "puc: growing-area codes; phc: packing-house codes."
          },
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "The destination market whose protocol the codes are registered for (ISO 3166-1 alpha-2)."
          },
          "crop": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$",
            "description": "One of the platform's crops (AGRITRACE_REGISTRY_CROPS; by default coconut, dragon_fruit, durian, jackfruit, mango)."
          },
          "source_url": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "The page the list was downloaded from."
          },
          "source_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the file the authority published (its spreadsheet or PDF), which the admin converted into the stored CSV. The server computed it when the original was uploaded (PUT /v1/registry-sources/{sha256}); it ties a Cross-checked registration step back to the authority's own file."
          },
          "source_media_type": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "application/pdf",
              "application/vnd.ms-excel",
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              "text/csv",
              null
            ],
            "description": "The media type of the authority's original file `source_sha256` names (GET /v1/registry-lists/{id}/source)."
          },
          "published_on": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The date the authority published the list, when known."
          },
          "file_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "file_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the stored file."
          },
          "file_size": {
            "type": "integer",
            "minimum": 1
          },
          "entry_count": {
            "type": "integer",
            "minimum": 0
          },
          "imported_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "imported_by": {
            "type": "string"
          },
          "superseded_by": {
            "type": [
              "integer",
              "null"
            ]
          },
          "superseded_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When a later import superseded the list, or when it was retired (then `superseded_by` is null)."
          },
          "retired_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who retired the list (POST /v1/registry-lists/{id}/retire); null unless retired."
          },
          "retire_reason": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200,
            "description": "Why the list was retired; null unless retired."
          },
          "current": {
            "type": "boolean",
            "description": "Neither superseded by a later import nor retired."
          },
          "stale": {
            "type": "boolean",
            "description": "Current and older than the configured age."
          },
          "status_counts": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "active",
              "suspended",
              "revoked"
            ],
            "properties": {
              "active": {
                "type": "integer",
                "minimum": 0
              },
              "suspended": {
                "type": "integer",
                "minimum": 0
              },
              "revoked": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "max_age_days": {
            "type": "integer",
            "minimum": 1,
            "maximum": 365
          }
        },
        "example": {
          "id": 3,
          "kind": "puc",
          "market": "CN",
          "crop": "durian",
          "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
          "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
          "source_media_type": "application/pdf",
          "published_on": "2026-09-25",
          "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
          "file_sha256": "9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f",
          "file_size": 48213,
          "entry_count": 812,
          "imported_at": 1790000000.5,
          "imported_by": "admin@croppath.example",
          "superseded_by": null,
          "superseded_at": null,
          "retired_by": null,
          "retire_reason": null,
          "current": true,
          "stale": false,
          "status_counts": {
            "active": 805,
            "suspended": 6,
            "revoked": 1
          },
          "max_age_days": 30
        }
      },
      "RegistryListPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "max_age_days",
          "crops",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/RegistryList"
            }
          },
          "max_age_days": {
            "type": "integer",
            "minimum": 1,
            "maximum": 365
          },
          "crops": {
            "type": "array",
            "minItems": 1,
            "maxItems": 50,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^[a-z][a-z0-9_]{0,63}$"
            },
            "description": "The crops an import may name, sorted (AGRITRACE_REGISTRY_CROPS; by default the D7 crops)."
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 3,
              "kind": "puc",
              "market": "CN",
              "crop": "durian",
              "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
              "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
              "source_media_type": "application/pdf",
              "published_on": "2026-09-25",
              "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
              "file_sha256": "9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f9c2f",
              "file_size": 48213,
              "entry_count": 812,
              "imported_at": 1790000000.5,
              "imported_by": "admin@croppath.example",
              "superseded_by": null,
              "superseded_at": null,
              "retired_by": null,
              "retire_reason": null,
              "current": true,
              "stale": false
            }
          ],
          "max_age_days": 30,
          "crops": [
            "coconut",
            "dragon_fruit",
            "durian",
            "jackfruit",
            "mango"
          ],
          "next_cursor": null
        }
      },
      "RegistryListEntry": {
        "type": "object",
        "description": "One row of an imported list: `code` normalised (NFKC, no whitespace, dashes as '-', upper case), `code_raw` as written in the file.",
        "additionalProperties": false,
        "required": [
          "code",
          "code_raw",
          "status",
          "holder",
          "province",
          "district",
          "commune",
          "area_ha",
          "valid_from",
          "valid_to"
        ],
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9._/-]{0,63}$"
          },
          "code_raw": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "suspended",
              "revoked"
            ]
          },
          "holder": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "commune": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "area_ha": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0
          },
          "valid_from": {
            "type": [
              "string",
              "null"
            ],
            "format": "date"
          },
          "valid_to": {
            "type": [
              "string",
              "null"
            ],
            "format": "date"
          }
        },
        "example": {
          "code": "VN-DLOR-0101",
          "code_raw": "VN-DLOR-0101",
          "status": "active",
          "holder": "HTX Krông Pắc",
          "province": "Đắk Lắk",
          "district": "Krông Pắc",
          "commune": "Ea Kly",
          "area_ha": 12.5,
          "valid_from": null,
          "valid_to": null
        }
      },
      "RegistryListEntryPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/RegistryListEntry"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "items": [
            {
              "code": "VN-DLOR-0101",
              "code_raw": "VN-DLOR-0101",
              "status": "active",
              "holder": "HTX Krông Pắc",
              "province": "Đắk Lắk",
              "district": "Krông Pắc",
              "commune": "Ea Kly",
              "area_ha": 12.5,
              "valid_from": null,
              "valid_to": null
            }
          ],
          "next_cursor": "eyJhZnRlciI6IlZOLURMT1ItMDEwMSJ9"
        }
      },
      "RegistryMatch": {
        "type": "object",
        "description": "A registered code and its check against the current lists.",
        "additionalProperties": false,
        "required": [
          "code",
          "tenant",
          "name",
          "crop",
          "registered_code",
          "normalized_code",
          "result",
          "stale",
          "list_id",
          "list_crop"
        ],
        "properties": {
          "code": {
            "type": "string",
            "description": "The growing area's or facility's own code."
          },
          "tenant": {
            "type": [
              "string",
              "null"
            ]
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "crop": {
            "type": [
              "string",
              "null"
            ],
            "description": "The growing area's crop; null for a facility."
          },
          "registered_code": {
            "type": "string",
            "description": "The PUC or PHC as entered."
          },
          "normalized_code": {
            "type": [
              "string",
              "null"
            ]
          },
          "result": {
            "type": "string",
            "enum": [
              "matched",
              "no_code",
              "no_list",
              "not_found",
              "mismatch",
              "suspended",
              "revoked",
              "expired"
            ]
          },
          "stale": {
            "type": "boolean"
          },
          "list_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The list that decided (null for mismatch, no_list, no_code)."
          },
          "list_crop": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "code": "VN-TGOR-0387",
          "tenant": "coop-dl",
          "name": "Vườn Ngũ Hiệp",
          "crop": "durian",
          "registered_code": "VN-TGOR-0387-PUC",
          "normalized_code": "VN-TGOR-0387-PUC",
          "result": "matched",
          "stale": false,
          "list_id": 3,
          "list_crop": "durian"
        }
      },
      "RegistryMatchPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "max_age_days",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/RegistryMatch"
            }
          },
          "max_age_days": {
            "type": "integer",
            "minimum": 1,
            "maximum": 365
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "items": [
            {
              "code": "VN-TGOR-0387",
              "tenant": "coop-dl",
              "name": "Vườn Ngũ Hiệp",
              "crop": "durian",
              "registered_code": "VN-TGOR-0387-PUC",
              "normalized_code": "VN-TGOR-0387-PUC",
              "result": "matched",
              "stale": false,
              "list_id": 3,
              "list_crop": "durian"
            }
          ],
          "max_age_days": 30,
          "next_cursor": null
        }
      },
      "RegistryListImport": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "kind",
          "market",
          "crop",
          "source_url",
          "source_sha256",
          "file_name",
          "file_base64"
        ],
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "puc",
              "phc"
            ]
          },
          "market": {
            "type": "string",
            "enum": [
              "CN"
            ],
            "description": "A destination market the platform ships to (ISO 3166-1 alpha-2)."
          },
          "crop": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "The list's crop: one of the platform's crops (AGRITRACE_REGISTRY_CROPS; by default coconut, dragon_fruit, durian, jackfruit, mango; the Vietnamese names of those are accepted), as GET /v1/registry-lists lists them in `crops`. Any other crop is refused, and so is an import that would make more than 200 lists current."
          },
          "source_url": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "pattern": "^https?://"
          },
          "source_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the file the authority published (its spreadsheet or PDF), downloaded from source_url, before the admin converted it to this CSV. It must name an original already uploaded with PUT /v1/registry-sources/{sha256}, whose hash the server computed; any other value is refused. Required: a Cross-checked step must trace back to the authority's own file."
          },
          "published_on": {
            "type": [
              "string",
              "null"
            ],
            "format": "date"
          },
          "file_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "file_base64": {
            "type": "string",
            "minLength": 1,
            "description": "The CSV file, base64-encoded."
          }
        },
        "example": {
          "kind": "puc",
          "market": "CN",
          "crop": "durian",
          "source_url": "https://www.ppd.gov.vn/tin-moi-nhat/danh-sach-vung-trong-va-co-so-dong-goi-sau-rieng-duoc-trung-quoc-phe-duyet.html",
          "source_sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
          "published_on": "2026-09-25",
          "file_name": "puc-sau-rieng-cn-2026-09-25.csv",
          "file_base64": "Y29kZSxzdGF0dXMKVk4tRExPUi0wMTAxLGFjdGl2ZQo="
        }
      },
      "RegistryListRetire": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Why the list is retired: 1 to 200 characters on one line."
          }
        },
        "example": {
          "reason": "imported for the wrong crop"
        }
      },
      "RegistrySourceStored": {
        "type": "object",
        "required": [
          "sha256",
          "media_type",
          "size"
        ],
        "additionalProperties": false,
        "description": "The authority's original file of a code list as the server stored it: `sha256` is computed from the bytes.",
        "properties": {
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "media_type": {
            "type": "string",
            "enum": [
              "application/pdf",
              "application/vnd.ms-excel",
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              "text/csv"
            ]
          },
          "size": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1048576
          }
        },
        "example": {
          "sha256": "4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d4b1d",
          "media_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          "size": 182044
        }
      },
      "PublicLabMarketApproval": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "market",
          "approved",
          "reference"
        ],
        "properties": {
          "market": {
            "$ref": "#/components/schemas/PublicMarket"
          },
          "approved": {
            "type": "boolean",
            "description": "True when an active approval of the lab for this market, valid on the signed date, lists every tested analyte. False: the lab is not on the approved list for the market (for at least one analyte), so the results cannot count as Lab-verified for that market and the lab step is at most Cross-checked (reason `lab_not_approved_for_market`)."
          },
          "reference": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicText"
              },
              {
                "type": "null"
              }
            ],
            "description": "The approval's reference as published (several joined by \"; \"); null when not approved."
          }
        }
      },
      "LabApproval": {
        "type": "object",
        "additionalProperties": false,
        "description": "#154: a lab's approval for a destination market (e.g. on the list of labs whose cadmium and auramine O reports GACC accepts for Vietnamese durian). A lab result counts toward Lab-verified for the report's market only when an active approval of its lab for that market, valid on the report's signed date (Asia/Ho_Chi_Minh), lists the analyte; otherwise the lab step stops at Cross-checked (reason `lab_not_approved_for_market`). A withdrawn approval never counts.",
        "required": [
          "id",
          "lab",
          "market",
          "approving_body",
          "reference",
          "analytes",
          "valid_from",
          "valid_to",
          "source_url",
          "evidence_sha256",
          "status",
          "in_force",
          "created_at",
          "created_by",
          "updated_at",
          "updated_by"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "lab": {
            "type": "string",
            "description": "Lab code."
          },
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "Destination market, ISO 3166-1 alpha-2."
          },
          "approving_body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "reference": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "The approval's reference as published (decision or list number)."
          },
          "analytes": {
            "type": "array",
            "minItems": 1,
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^[a-z][a-z0-9_]{0,63}$"
            },
            "description": "Analyte codes the approval covers, sorted."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "description": "First valid day, inclusive."
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "description": "Last valid day, inclusive."
          },
          "source_url": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 2000,
            "description": "Where the list is published (http or https); stored and shown, never fetched."
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the list document kept as evidence."
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "withdrawn"
            ],
            "description": "`withdrawn`: recorded in error or revoked from the start; it never counts."
          },
          "in_force": {
            "type": "boolean",
            "description": "Active and valid today (Asia/Ho_Chi_Minh)."
          },
          "created_at": {
            "type": "number"
          },
          "created_by": {
            "type": "string"
          },
          "updated_at": {
            "type": "number"
          },
          "updated_by": {
            "type": "string"
          }
        },
        "example": {
          "id": 7,
          "lab": "LAB-VN-118",
          "market": "CN",
          "approving_body": "Plant Protection Department (MAE)",
          "reference": "List of approved labs, 2026-08-07, No. 17",
          "analytes": [
            "auramine_o",
            "cadmium"
          ],
          "valid_from": "2026-08-07",
          "valid_to": "2027-08-06",
          "source_url": "https://example.org/approved-labs-2026",
          "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
          "status": "active",
          "in_force": true,
          "created_at": 1790000000.5,
          "created_by": "admin@platform.example",
          "updated_at": 1790000000.5,
          "updated_by": "admin@platform.example"
        }
      },
      "LabApprovalList": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/LabApproval"
            }
          }
        },
        "description": "Every approval of the lab (at most 100), by market, then newest valid_from first."
      },
      "LabCompany": {
        "type": "object",
        "additionalProperties": false,
        "x-not-in-sdk": true,
        "description": "#278: a company a lab serves.",
        "required": [
          "lab",
          "tenant",
          "name",
          "linked_at"
        ],
        "properties": {
          "lab": {
            "type": "string",
            "description": "The lab's code."
          },
          "tenant": {
            "type": "string",
            "description": "The company's id."
          },
          "name": {
            "type": "string",
            "description": "The company's name."
          },
          "linked_at": {
            "type": "number",
            "description": "When the link was made (Unix seconds); for a link migration 113 made from the samplings already assigned, the first of them."
          }
        }
      },
      "LabCompanyList": {
        "type": "object",
        "additionalProperties": false,
        "x-not-in-sdk": true,
        "description": "#278: the companies a lab serves, by company id (at most 500).",
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 500,
            "items": {
              "$ref": "#/components/schemas/LabCompany"
            }
          }
        }
      },
      "LabApprovalCreate": {
        "type": "object",
        "additionalProperties": false,
        "description": "A new approval (status active). valid_to is on or after valid_from; source_url and evidence_sha256 are optional.",
        "required": [
          "market",
          "approving_body",
          "reference",
          "analytes",
          "valid_from",
          "valid_to"
        ],
        "properties": {
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "Destination market, ISO 3166-1 alpha-2."
          },
          "approving_body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "reference": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "The approval's reference as published (decision or list number)."
          },
          "analytes": {
            "type": "array",
            "minItems": 1,
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^[a-z][a-z0-9_]{0,63}$"
            },
            "description": "Analyte codes the approval covers, sorted."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "description": "First valid day, inclusive."
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "description": "Last valid day, inclusive."
          },
          "source_url": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 2000,
            "description": "Where the list is published (http or https); stored and shown, never fetched."
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the list document kept as evidence."
          }
        },
        "example": {
          "market": "CN",
          "approving_body": "Plant Protection Department (MAE)",
          "reference": "List of approved labs, 2026-08-07, No. 17",
          "analytes": [
            "auramine_o",
            "cadmium"
          ],
          "valid_from": "2026-08-07",
          "valid_to": "2027-08-06",
          "source_url": "https://example.org/approved-labs-2026",
          "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f"
        }
      },
      "LabApprovalUpdate": {
        "type": "object",
        "additionalProperties": false,
        "minProperties": 1,
        "description": "Any of the editable fields (the market never changes: record a new approval). null clears source_url or evidence_sha256; status `withdrawn` withdraws the approval (nothing is deleted).",
        "properties": {
          "approving_body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "reference": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "The approval's reference as published (decision or list number)."
          },
          "analytes": {
            "type": "array",
            "minItems": 1,
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^[a-z][a-z0-9_]{0,63}$"
            },
            "description": "Analyte codes the approval covers, sorted."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "description": "First valid day, inclusive."
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "description": "Last valid day, inclusive."
          },
          "source_url": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 2000,
            "description": "Where the list is published (http or https); stored and shown, never fetched."
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the list document kept as evidence."
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "withdrawn"
            ],
            "description": "`withdrawn`: recorded in error or revoked from the start; it never counts."
          }
        },
        "example": {
          "valid_to": "2026-12-31"
        }
      },
      "WebhookEventType": {
        "type": "string",
        "description": "An event a subscription can take: `lot.sealed` (a lot closed and signed), `lot.recalled` and `lot.withdrawn` (a recall or withdrawal), `lab_result.recorded` (a lab report stored, from the lab's signature or its portal), `shipment.departed` (the ship event), `lot.trust_tier_changed` (the displayed trust tier of a lot moved) and `report.filed` (a public mismatch report on one of the tenant's fruits).",
        "enum": [
          "lot.sealed",
          "lot.recalled",
          "lot.withdrawn",
          "lab_result.recorded",
          "shipment.departed",
          "lot.trust_tier_changed",
          "report.filed"
        ]
      },
      "WebhookSubscription": {
        "type": "object",
        "description": "A webhook subscription of the tenant: never its secret (stored encrypted, shown once by create and by rotate-secret). Unix seconds.",
        "additionalProperties": false,
        "required": [
          "id",
          "url",
          "description",
          "event_types",
          "status",
          "disabled_reason",
          "disabled_at",
          "consecutive_failures",
          "created_by",
          "created_at",
          "updated_at"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "url": {
            "type": "string",
            "pattern": "^https://",
            "maxLength": 2048,
            "description": "The endpoint: https only, no credentials, no fragment; every address its host resolves to is public (checked when set and again at every delivery)."
          },
          "description": {
            "type": "string",
            "maxLength": 200
          },
          "event_types": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/WebhookEventType"
            }
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "disabled"
            ],
            "description": "Only an active subscription takes new events and is delivered to."
          },
          "disabled_reason": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "manual",
              "failures",
              null
            ],
            "description": "`manual`: turned off by an admin; `failures`: 50 failed attempts in a row. null while active."
          },
          "disabled_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "consecutive_failures": {
            "type": "integer",
            "minimum": 0,
            "description": "Failed delivery attempts since the last success."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "updated_at": {
            "type": "number"
          }
        },
        "example": {
          "id": 3,
          "url": "https://erp.buyer.example/hooks/croppath",
          "description": "Buyer ERP",
          "event_types": [
            "lot.sealed",
            "shipment.departed"
          ],
          "status": "active",
          "disabled_reason": null,
          "disabled_at": null,
          "consecutive_failures": 0,
          "created_by": "admin@coop.example",
          "created_at": 1790000000.5,
          "updated_at": 1790000000.5
        }
      },
      "WebhookSubscriptionList": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/WebhookSubscription"
            }
          }
        },
        "example": {
          "items": [
            {
              "id": 3,
              "url": "https://erp.buyer.example/hooks/croppath",
              "description": "Buyer ERP",
              "event_types": [
                "lot.sealed",
                "shipment.departed"
              ],
              "status": "active",
              "disabled_reason": null,
              "disabled_at": null,
              "consecutive_failures": 0,
              "created_by": "admin@coop.example",
              "created_at": 1790000000.5,
              "updated_at": 1790000000.5
            }
          ]
        }
      },
      "WebhookSubscriptionCreate": {
        "type": "object",
        "description": "A tenant holds at most 20 subscriptions. The secret is generated by the server.",
        "additionalProperties": false,
        "required": [
          "url",
          "event_types"
        ],
        "properties": {
          "url": {
            "type": "string",
            "pattern": "^https://",
            "minLength": 9,
            "maxLength": 2048
          },
          "event_types": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/WebhookEventType"
            }
          },
          "description": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "One line."
          }
        },
        "example": {
          "url": "https://erp.buyer.example/hooks/croppath",
          "event_types": [
            "lot.sealed",
            "shipment.departed"
          ],
          "description": "Buyer ERP"
        }
      },
      "WebhookSubscriptionUpdate": {
        "type": "object",
        "description": "At least one field. `enabled: false` disables the subscription (`manual`) and fails its pending deliveries (`subscription_disabled`); `enabled: true` makes it active again with no failures counted.",
        "additionalProperties": false,
        "minProperties": 1,
        "properties": {
          "url": {
            "type": "string",
            "pattern": "^https://",
            "minLength": 9,
            "maxLength": 2048
          },
          "event_types": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true,
            "items": {
              "$ref": "#/components/schemas/WebhookEventType"
            }
          },
          "description": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "enabled": {
            "type": "boolean"
          }
        },
        "example": {
          "enabled": false
        }
      },
      "WebhookSecret": {
        "type": "object",
        "description": "The subscription and, in `secret`, its signing secret: this response is the only place it appears (Standard Webhooks format: `whsec_` + base64 of 32 random bytes; the HMAC key is the decoded bytes). Store it now; a lost secret is rotated.",
        "additionalProperties": false,
        "required": [
          "subscription",
          "secret"
        ],
        "properties": {
          "subscription": {
            "$ref": "#/components/schemas/WebhookSubscription"
          },
          "secret": {
            "type": "string",
            "pattern": "^whsec_[A-Za-z0-9+/]{43}=$"
          }
        },
        "example": {
          "subscription": {
            "id": 3,
            "url": "https://erp.buyer.example/hooks/croppath",
            "description": "Buyer ERP",
            "event_types": [
              "lot.sealed",
              "shipment.departed"
            ],
            "status": "active",
            "disabled_reason": null,
            "disabled_at": null,
            "consecutive_failures": 0,
            "created_by": "admin@coop.example",
            "created_at": 1790000000.5,
            "updated_at": 1790000000.5
          },
          "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw3qdbLeXcY4o="
        }
      },
      "WebhookDelivery": {
        "type": "object",
        "description": "One delivery of one event to the subscription: `pending` (attempted at `next_attempt_at`), `delivered` (a 2xx answer) or `failed` (12 attempts over about 21 hours, or the subscription was disabled). Unix seconds.",
        "additionalProperties": false,
        "required": [
          "id",
          "subscription_id",
          "event_id",
          "event_type",
          "status",
          "attempts",
          "next_attempt_at",
          "last_attempt_at",
          "last_status",
          "last_error",
          "created_at",
          "delivered_at"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "subscription_id": {
            "type": "integer",
            "minimum": 1
          },
          "event_id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "The `webhook-id` header: the same on every attempt and redelivery."
          },
          "event_type": {
            "$ref": "#/components/schemas/WebhookEventType"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "delivered",
              "failed"
            ]
          },
          "attempts": {
            "type": "integer",
            "minimum": 0,
            "description": "Since the delivery was queued or redelivered."
          },
          "next_attempt_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "last_attempt_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "last_status": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The last attempt's HTTP status; null: none."
          },
          "last_error": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64,
            "description": "Why the last attempt failed: `http_status` (a non-2xx answer, a redirect included), `blocked_address` (the host resolved to an address that is not public), `dns_failure`, `connect_failed`, `tls_error`, `timeout` (10 seconds for the whole attempt), `protocol_error`, `invalid_url`, `secret_unavailable`, `subscription_disabled`, `internal_error`."
          },
          "created_at": {
            "type": "number"
          },
          "delivered_at": {
            "type": [
              "number",
              "null"
            ]
          }
        },
        "example": {
          "id": 41,
          "subscription_id": 3,
          "event_id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "event_type": "lot.sealed",
          "status": "delivered",
          "attempts": 1,
          "next_attempt_at": null,
          "last_attempt_at": 1790000003.2,
          "last_status": 204,
          "last_error": null,
          "created_at": 1790000002.9,
          "delivered_at": 1790000003.4
        }
      },
      "WebhookDeliveryPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/WebhookDelivery"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 41,
              "subscription_id": 3,
              "event_id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
              "event_type": "lot.sealed",
              "status": "delivered",
              "attempts": 1,
              "next_attempt_at": null,
              "last_attempt_at": 1790000003.2,
              "last_status": 204,
              "last_error": null,
              "created_at": 1790000002.9,
              "delivered_at": 1790000003.4
            }
          ],
          "next_cursor": null
        }
      },
      "WebhookLotSealedData": {
        "type": "object",
        "description": "`lot.sealed`: the lot was closed and its manifest signed (L10).",
        "additionalProperties": false,
        "required": [
          "lot",
          "public_id",
          "facility",
          "sealed_at",
          "manifest_sha256",
          "fruit_count",
          "event_count"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "minLength": 1
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "The lot's public id (its QR record)."
          },
          "facility": {
            "type": "string",
            "minLength": 1
          },
          "sealed_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "manifest_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "fruit_count": {
            "type": "integer",
            "minimum": 0
          },
          "event_count": {
            "type": "integer",
            "minimum": 0
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "public_id": "9f86d081884c7d659a2feaa0c55ad015",
          "facility": "VN-TGPH-021",
          "sealed_at": "2026-09-28T10:15:00.000Z",
          "manifest_sha256": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
          "fruit_count": 128,
          "event_count": 260
        }
      },
      "WebhookLotRecalledData": {
        "type": "object",
        "description": "`lot.recalled` and `lot.withdrawn`: the lot's recall or withdrawal (P5). The staff note never appears.",
        "additionalProperties": false,
        "required": [
          "lot",
          "public_id",
          "kind",
          "reason",
          "scope",
          "recalled_at",
          "cartons",
          "shipments"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "minLength": 1
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "The lot's public id (its QR record)."
          },
          "kind": {
            "type": "string",
            "enum": [
              "recall",
              "withdrawal"
            ]
          },
          "reason": {
            "type": "string",
            "enum": [
              "contamination",
              "pathogen",
              "foreign_matter",
              "labelling",
              "quality",
              "regulatory",
              "traceability",
              "other"
            ]
          },
          "scope": {
            "type": "string",
            "enum": [
              "consumer",
              "retail",
              "wholesale"
            ]
          },
          "recalled_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "cartons": {
            "type": "integer",
            "minimum": 0
          },
          "shipments": {
            "type": "integer",
            "minimum": 0
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "public_id": "9f86d081884c7d659a2feaa0c55ad015",
          "kind": "recall",
          "reason": "contamination",
          "scope": "consumer",
          "recalled_at": "2026-10-02T03:00:00.000Z",
          "cartons": 41,
          "shipments": 1
        }
      },
      "WebhookLabResultRecordedData": {
        "type": "object",
        "description": "`lab_result.recorded`: a lab report of the lot's sampling was stored; `passed` is the verdict against the market's limits (the values are read through the API).",
        "additionalProperties": false,
        "required": [
          "lot",
          "sampling_id",
          "lab",
          "report_no",
          "market",
          "signed_at",
          "passed"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "minLength": 1
          },
          "sampling_id": {
            "type": "integer",
            "minimum": 1
          },
          "lab": {
            "type": "string",
            "minLength": 1
          },
          "report_no": {
            "type": "string",
            "minLength": 1
          },
          "market": {
            "type": "string",
            "minLength": 2,
            "maxLength": 2
          },
          "signed_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "passed": {
            "type": "boolean"
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "sampling_id": 12,
          "lab": "LAB-VN-118",
          "report_no": "KN-LO-260928-014",
          "market": "CN",
          "signed_at": "2026-09-29T02:00:00.000Z",
          "passed": true
        }
      },
      "WebhookShipmentDepartedData": {
        "type": "object",
        "description": "`shipment.departed`: the shipment left its facility; its lots are shipped.",
        "additionalProperties": false,
        "required": [
          "shipment",
          "facility",
          "container",
          "border_gate",
          "destination",
          "departed_at",
          "lots"
        ],
        "properties": {
          "shipment": {
            "type": "string",
            "minLength": 1
          },
          "facility": {
            "type": "string",
            "minLength": 1
          },
          "container": {
            "type": "string",
            "minLength": 1
          },
          "border_gate": {
            "type": "string",
            "minLength": 1
          },
          "destination": {
            "type": "string",
            "minLength": 1
          },
          "departed_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "lots": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "string",
              "minLength": 1
            }
          }
        },
        "example": {
          "shipment": "SH-LO-260928-014",
          "facility": "VN-TGPH-021",
          "container": "MSKU1234565",
          "border_gate": "Hữu Nghị",
          "destination": "CN",
          "departed_at": "2026-09-29T09:00:00.000Z",
          "lots": [
            "LO-260928-014"
          ]
        }
      },
      "WebhookTrustTierChangedData": {
        "type": "object",
        "description": "`lot.trust_tier_changed`: a recompute moved the lot's displayed trust tier (ADR 0001; a hold drops it to self_declared, its resolution restores at most the sealed tier). Not sent for a lot's first snapshot.",
        "additionalProperties": false,
        "required": [
          "lot",
          "public_id",
          "tier",
          "previous_tier",
          "status",
          "changed_at"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "minLength": 1
          },
          "public_id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "The lot's public id (its QR record)."
          },
          "tier": {
            "$ref": "#/components/schemas/TrustTier"
          },
          "previous_tier": {
            "$ref": "#/components/schemas/TrustTier"
          },
          "status": {
            "type": "string",
            "enum": [
              "normal",
              "on_hold"
            ]
          },
          "changed_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "public_id": "9f86d081884c7d659a2feaa0c55ad015",
          "tier": "self_declared",
          "previous_tier": "cross_checked",
          "status": "on_hold",
          "changed_at": "2026-10-01T05:30:00.000Z"
        }
      },
      "WebhookReportFiledData": {
        "type": "object",
        "description": "`report.filed`: a consumer filed a mismatch report on one of the lot's fruits (X5). The note and the contact never appear.",
        "additionalProperties": false,
        "required": [
          "report_id",
          "lot",
          "fruit",
          "category",
          "filed_at"
        ],
        "properties": {
          "report_id": {
            "type": "integer",
            "minimum": 1
          },
          "lot": {
            "type": "string",
            "minLength": 1
          },
          "fruit": {
            "type": "string",
            "minLength": 1
          },
          "category": {
            "type": "string",
            "enum": [
              "label_peeled",
              "scanned_many",
              "ripeness_off",
              "other"
            ]
          },
          "filed_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          }
        },
        "example": {
          "report_id": 5,
          "lot": "LO-260928-014",
          "fruit": "Q-14-37",
          "category": "ripeness_off",
          "filed_at": "2026-10-01T05:29:58.000Z"
        }
      },
      "WebhookEventLotSealed": {
        "type": "object",
        "description": "The body of a `lot.sealed` delivery (compact JSON, UTF-8).",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "created_at",
          "tenant",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "Equals `webhook-id`."
          },
          "type": {
            "const": "lot.sealed"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "tenant": {
            "type": "string",
            "minLength": 1
          },
          "data": {
            "$ref": "#/components/schemas/WebhookLotSealedData"
          }
        },
        "example": {
          "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "type": "lot.sealed",
          "created_at": "2026-10-01T05:30:00.000Z",
          "tenant": "coop-dl",
          "data": {
            "lot": "LO-260928-014",
            "public_id": "9f86d081884c7d659a2feaa0c55ad015",
            "facility": "VN-TGPH-021",
            "sealed_at": "2026-09-28T10:15:00.000Z",
            "manifest_sha256": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
            "fruit_count": 128,
            "event_count": 260
          }
        }
      },
      "WebhookEventLotRecalled": {
        "type": "object",
        "description": "The body of a `lot.recalled` delivery (compact JSON, UTF-8).",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "created_at",
          "tenant",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "Equals `webhook-id`."
          },
          "type": {
            "const": "lot.recalled"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "tenant": {
            "type": "string",
            "minLength": 1
          },
          "data": {
            "$ref": "#/components/schemas/WebhookLotRecalledData"
          }
        },
        "example": {
          "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "type": "lot.recalled",
          "created_at": "2026-10-01T05:30:00.000Z",
          "tenant": "coop-dl",
          "data": {
            "lot": "LO-260928-014",
            "public_id": "9f86d081884c7d659a2feaa0c55ad015",
            "kind": "recall",
            "reason": "contamination",
            "scope": "consumer",
            "recalled_at": "2026-10-02T03:00:00.000Z",
            "cartons": 41,
            "shipments": 1
          }
        }
      },
      "WebhookEventLotWithdrawn": {
        "type": "object",
        "description": "The body of a `lot.withdrawn` delivery (compact JSON, UTF-8).",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "created_at",
          "tenant",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "Equals `webhook-id`."
          },
          "type": {
            "const": "lot.withdrawn"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "tenant": {
            "type": "string",
            "minLength": 1
          },
          "data": {
            "$ref": "#/components/schemas/WebhookLotRecalledData"
          }
        },
        "example": {
          "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "type": "lot.withdrawn",
          "created_at": "2026-10-01T05:30:00.000Z",
          "tenant": "coop-dl",
          "data": {
            "lot": "LO-260928-014",
            "public_id": "9f86d081884c7d659a2feaa0c55ad015",
            "kind": "withdrawal",
            "reason": "contamination",
            "scope": "consumer",
            "recalled_at": "2026-10-02T03:00:00.000Z",
            "cartons": 41,
            "shipments": 1
          }
        }
      },
      "WebhookEventLabResultRecorded": {
        "type": "object",
        "description": "The body of a `lab_result.recorded` delivery (compact JSON, UTF-8).",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "created_at",
          "tenant",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "Equals `webhook-id`."
          },
          "type": {
            "const": "lab_result.recorded"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "tenant": {
            "type": "string",
            "minLength": 1
          },
          "data": {
            "$ref": "#/components/schemas/WebhookLabResultRecordedData"
          }
        },
        "example": {
          "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "type": "lab_result.recorded",
          "created_at": "2026-10-01T05:30:00.000Z",
          "tenant": "coop-dl",
          "data": {
            "lot": "LO-260928-014",
            "sampling_id": 12,
            "lab": "LAB-VN-118",
            "report_no": "KN-LO-260928-014",
            "market": "CN",
            "signed_at": "2026-09-29T02:00:00.000Z",
            "passed": true
          }
        }
      },
      "WebhookEventShipmentDeparted": {
        "type": "object",
        "description": "The body of a `shipment.departed` delivery (compact JSON, UTF-8).",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "created_at",
          "tenant",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "Equals `webhook-id`."
          },
          "type": {
            "const": "shipment.departed"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "tenant": {
            "type": "string",
            "minLength": 1
          },
          "data": {
            "$ref": "#/components/schemas/WebhookShipmentDepartedData"
          }
        },
        "example": {
          "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "type": "shipment.departed",
          "created_at": "2026-10-01T05:30:00.000Z",
          "tenant": "coop-dl",
          "data": {
            "shipment": "SH-LO-260928-014",
            "facility": "VN-TGPH-021",
            "container": "MSKU1234565",
            "border_gate": "Hữu Nghị",
            "destination": "CN",
            "departed_at": "2026-09-29T09:00:00.000Z",
            "lots": [
              "LO-260928-014"
            ]
          }
        }
      },
      "WebhookEventLotTrustTierChanged": {
        "type": "object",
        "description": "The body of a `lot.trust_tier_changed` delivery (compact JSON, UTF-8).",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "created_at",
          "tenant",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "Equals `webhook-id`."
          },
          "type": {
            "const": "lot.trust_tier_changed"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "tenant": {
            "type": "string",
            "minLength": 1
          },
          "data": {
            "$ref": "#/components/schemas/WebhookTrustTierChangedData"
          }
        },
        "example": {
          "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "type": "lot.trust_tier_changed",
          "created_at": "2026-10-01T05:30:00.000Z",
          "tenant": "coop-dl",
          "data": {
            "lot": "LO-260928-014",
            "public_id": "9f86d081884c7d659a2feaa0c55ad015",
            "tier": "self_declared",
            "previous_tier": "cross_checked",
            "status": "on_hold",
            "changed_at": "2026-10-01T05:30:00.000Z"
          }
        }
      },
      "WebhookEventReportFiled": {
        "type": "object",
        "description": "The body of a `report.filed` delivery (compact JSON, UTF-8).",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "created_at",
          "tenant",
          "data"
        ],
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{32}$",
            "description": "Equals `webhook-id`."
          },
          "type": {
            "const": "report.filed"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "UTC, ISO 8601 with milliseconds."
          },
          "tenant": {
            "type": "string",
            "minLength": 1
          },
          "data": {
            "$ref": "#/components/schemas/WebhookReportFiledData"
          }
        },
        "example": {
          "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
          "type": "report.filed",
          "created_at": "2026-10-01T05:30:00.000Z",
          "tenant": "coop-dl",
          "data": {
            "report_id": 5,
            "lot": "LO-260928-014",
            "fruit": "Q-14-37",
            "category": "ripeness_off",
            "filed_at": "2026-10-01T05:29:58.000Z"
          }
        }
      },
      "ExportLabelText": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "zh",
          "en"
        ],
        "properties": {
          "zh": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120
          },
          "en": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120
          }
        },
        "description": "A text of the label in Chinese (`zh`) and English (`en`)."
      },
      "ExportLabelFieldTemplate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "zh",
          "en",
          "required"
        ],
        "description": "A field's caption in Chinese and English and whether the label is refused without a value.",
        "properties": {
          "zh": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120
          },
          "en": {
            "type": "string",
            "minLength": 1,
            "maxLength": 120
          },
          "required": {
            "type": "boolean"
          }
        }
      },
      "ExportLabelTemplate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "mark",
          "export_country",
          "products",
          "fields",
          "require_cross_checked_codes",
          "source"
        ],
        "description": "A destination market's label template, text only: the mark on every package and pallet, the export country, the fruit name of each lot product, each field's captions and whether it is required, whether the PUC and PHC codes must be cross-checked, and the rule it follows. Texts are 1 to 120 characters on one line.",
        "properties": {
          "mark": {
            "$ref": "#/components/schemas/ExportLabelText"
          },
          "export_country": {
            "$ref": "#/components/schemas/ExportLabelText"
          },
          "products": {
            "type": "object",
            "minProperties": 1,
            "maxProperties": 50,
            "description": "The fruit name per lot product (`lots.product`, e.g. durian).",
            "additionalProperties": {
              "$ref": "#/components/schemas/ExportLabelText"
            }
          },
          "fields": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "fruit",
              "origin",
              "export_country",
              "orchard",
              "packing_house",
              "packing_date",
              "net_mass",
              "count",
              "lot"
            ],
            "properties": {
              "fruit": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "origin": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "export_country": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "orchard": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "packing_house": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "producer": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate",
                "description": "#186: the producer (legal name and address from the company profile). Always present in a response; a request may leave it out, and then it gets the built-in captions and is not required."
              },
              "packing_date": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "net_mass": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "count": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              },
              "lot": {
                "$ref": "#/components/schemas/ExportLabelFieldTemplate"
              }
            }
          },
          "require_cross_checked_codes": {
            "type": "boolean",
            "description": "When true, a label whose PUC or PHC code is not cross-checked against the published code lists is not ready for export."
          },
          "source": {
            "type": "string",
            "minLength": 1,
            "maxLength": 1000
          }
        },
        "example": {
          "mark": {
            "zh": "输往中华人民共和国",
            "en": "Exported to the People's Republic of China"
          },
          "export_country": {
            "zh": "越南",
            "en": "Vietnam"
          },
          "products": {
            "durian": {
              "zh": "榴莲",
              "en": "Durian"
            }
          },
          "fields": {
            "fruit": {
              "zh": "水果名称",
              "en": "Fruit",
              "required": true
            },
            "origin": {
              "zh": "产地",
              "en": "Origin",
              "required": true
            },
            "export_country": {
              "zh": "出口国家",
              "en": "Country of export",
              "required": true
            },
            "orchard": {
              "zh": "果园名称或注册号",
              "en": "Orchard name or registration number",
              "required": true
            },
            "packing_house": {
              "zh": "包装厂名称或注册号",
              "en": "Packing house name or registration number",
              "required": true
            },
            "producer": {
              "zh": "生产商",
              "en": "Producer",
              "required": false
            },
            "packing_date": {
              "zh": "包装日期",
              "en": "Packing date",
              "required": false
            },
            "net_mass": {
              "zh": "净重",
              "en": "Net weight",
              "required": false
            },
            "count": {
              "zh": "数量",
              "en": "Count",
              "required": false
            },
            "lot": {
              "zh": "批号",
              "en": "Lot",
              "required": false
            }
          },
          "require_cross_checked_codes": true,
          "source": "Durian export label clause as published for the Malaysia and Laos protocols with China (same clause family as the Vietnam-China protocol of 2022-07-11; to be confirmed against the Vietnamese text): https://www.doa.gov.my/doa/resources/aktiviti_sumber/sumber_awam/maklumat_biosekuriti/pamplet_prosedur_pengeksportan_durian_segar_ke_china.pdf"
        }
      },
      "ExportLabelTemplateView": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "market",
          "version",
          "template",
          "updated_at",
          "updated_by"
        ],
        "description": "A market's template in force: version 0 is the built-in default (no edit yet).",
        "properties": {
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$"
          },
          "version": {
            "type": "integer",
            "minimum": 0
          },
          "template": {
            "$ref": "#/components/schemas/ExportLabelTemplate"
          },
          "updated_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "updated_by": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "ExportLabelTemplateList": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExportLabelTemplateView"
            }
          }
        }
      },
      "ExportLabelCodeField": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "name",
          "code",
          "check",
          "cross_checked"
        ],
        "properties": {
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "code": {
            "type": [
              "string",
              "null"
            ],
            "description": "The registration code, only when cross-checked; null otherwise (never printed unchecked)."
          },
          "check": {
            "type": "string",
            "enum": [
              "matched",
              "no_code",
              "no_list",
              "not_found",
              "mismatch",
              "suspended",
              "revoked",
              "expired"
            ],
            "description": "The code against the published code lists (#150): `no_list` while no list exists."
          },
          "cross_checked": {
            "type": "boolean",
            "description": "Matched on a list that is not stale."
          }
        },
        "description": "The orchard (growing area, PUC code) or the packing house (facility, PHC code)."
      },
      "ExportLabelCarton": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "carton_no",
          "net_mass_kg",
          "fruit_count",
          "qr_url"
        ],
        "properties": {
          "code": {
            "type": "string"
          },
          "carton_no": {
            "type": "integer",
            "minimum": 1
          },
          "net_mass_kg": {
            "type": [
              "number",
              "null"
            ]
          },
          "fruit_count": {
            "type": "integer",
            "minimum": 0
          },
          "qr_url": {
            "type": "string",
            "format": "uri",
            "description": "The carton's public URL: a GS1 Digital Link with the lot's GTIN, else `<resolver>/q/<public id>`."
          },
          "label_code": {
            "type": "string",
            "pattern": "^[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}$",
            "description": "#288, with `label_code=1` only: the carton's lookup code in its grouped form (three groups of five Crockford base 32 characters), derived from the carton's public id. A person types it on the scan page when the QR code cannot be scanned; `GET /v1/public/resolve` answers it with the carton's lot.",
            "example": "7YD1R-1YMWA-W5MVB",
            "x-not-in-sdk": true
          }
        }
      },
      "ExportLabel": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "market",
          "lot_status",
          "template_version",
          "template",
          "fields",
          "pallet",
          "cartons",
          "problems",
          "ready",
          "next_cursor"
        ],
        "description": "What a lot's export carton and pallet labels print for a market, and why they are not ready for export (`problems`, empty when `ready`).",
        "properties": {
          "lot": {
            "type": "string"
          },
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$"
          },
          "lot_status": {
            "type": "string"
          },
          "template_version": {
            "type": "integer",
            "minimum": 0
          },
          "template": {
            "$ref": "#/components/schemas/ExportLabelTemplate"
          },
          "fields": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "fruit",
              "origin",
              "export_country",
              "orchard",
              "packing_house",
              "producer",
              "packing_date"
            ],
            "properties": {
              "fruit": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/ExportLabelText"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "The template's name of the lot's product; null when it has none."
              },
              "origin": {
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "province",
                      "district"
                    ],
                    "properties": {
                      "province": {
                        "type": "string"
                      },
                      "district": {
                        "type": "string"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "province",
                      "commune",
                      "district"
                    ],
                    "description": "#273, with `admin_units=1` only: the origin with its commune. A coded growing area has its commune and province and `district` null; an area not coded yet has its province and district and its commune text, if any.",
                    "properties": {
                      "province": {
                        "type": "string"
                      },
                      "commune": {
                        "type": [
                          "string",
                          "null"
                        ]
                      },
                      "district": {
                        "type": [
                          "string",
                          "null"
                        ]
                      }
                    }
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "The growing area's origin; null when it is incomplete. #273: a growing area coded by official administrative unit codes needs its province and commune and an area not coded yet its province and district. Without `admin_units=1` the origin is `{province, district}` for an area not coded yet and null for a coded one; with it, `{province, commune, district}`.",
                "x-sdk-object": {
                  "oneOf": [
                    {
                      "type": "object",
                      "additionalProperties": false,
                      "required": [
                        "province",
                        "district"
                      ],
                      "properties": {
                        "province": {
                          "type": "string"
                        },
                        "district": {
                          "type": "string"
                        }
                      }
                    },
                    {
                      "type": "null"
                    }
                  ],
                  "description": "The growing area's province and district; null when either is missing."
                }
              },
              "export_country": {
                "$ref": "#/components/schemas/ExportLabelText"
              },
              "orchard": {
                "$ref": "#/components/schemas/ExportLabelCodeField"
              },
              "packing_house": {
                "$ref": "#/components/schemas/ExportLabelCodeField"
              },
              "producer": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/CompanyProducer"
                  },
                  {
                    "type": "null"
                  }
                ],
                "description": "#186: the lot's company from its company profile (legal name and address); null until the company saves a profile."
              },
              "packing_date": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date",
                "description": "The pack day in Asia/Ho_Chi_Minh; null before the lot is packed."
              }
            }
          },
          "pallet": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "from",
              "to",
              "cartons",
              "fruit_count",
              "net_mass_kg",
              "qr_url"
            ],
            "description": "The selected cartons' totals (the pallet label) and the lot's public URL.",
            "properties": {
              "from": {
                "type": [
                  "integer",
                  "null"
                ]
              },
              "to": {
                "type": [
                  "integer",
                  "null"
                ]
              },
              "cartons": {
                "type": "integer",
                "minimum": 0
              },
              "fruit_count": {
                "type": "integer",
                "minimum": 0
              },
              "net_mass_kg": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "qr_url": {
                "type": "string",
                "format": "uri"
              }
            }
          },
          "cartons": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExportLabelCarton"
            }
          },
          "problems": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "lot_not_packed",
                "lot_recalled",
                "shipment_market_mismatch",
                "fruit_missing",
                "origin_missing",
                "export_country_missing",
                "orchard_missing",
                "packing_house_missing",
                "producer_missing",
                "packing_date_missing",
                "address_not_coded",
                "orchard_code_not_cross_checked",
                "packing_house_code_not_cross_checked",
                "no_cartons"
              ],
              "x-sdk-enum": [
                "lot_not_packed",
                "lot_recalled",
                "shipment_market_mismatch",
                "fruit_missing",
                "origin_missing",
                "export_country_missing",
                "orchard_missing",
                "packing_house_missing",
                "producer_missing",
                "packing_date_missing",
                "orchard_code_not_cross_checked",
                "packing_house_code_not_cross_checked",
                "no_cartons"
              ]
            }
          },
          "ready": {
            "type": "boolean"
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "ExportLabelPrintCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "market",
          "kind",
          "template_version",
          "cartons"
        ],
        "properties": {
          "market": {
            "type": "string",
            "pattern": "^[A-Z]{2}$"
          },
          "kind": {
            "type": "string",
            "enum": [
              "carton",
              "pallet"
            ]
          },
          "from": {
            "type": "integer",
            "minimum": 1,
            "maximum": 9999
          },
          "to": {
            "type": "integer",
            "minimum": 1,
            "maximum": 9999
          },
          "template_version": {
            "type": "integer",
            "minimum": 0,
            "maximum": 2147483647,
            "description": "The template version of the label the console read and prints (ExportLabel.template_version); 409 label_changed when another version is in force."
          },
          "cartons": {
            "type": "integer",
            "minimum": 0,
            "maximum": 9999,
            "description": "The selection's carton count the console read (ExportLabel.pallet.cartons); 409 label_changed when the selection now holds another count."
          }
        }
      },
      "ExportLabelPrint": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "lot",
          "market",
          "kind",
          "from",
          "to",
          "cartons",
          "template_version",
          "printed_by",
          "printed_at"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "lot": {
            "type": "string"
          },
          "market": {
            "type": "string"
          },
          "kind": {
            "type": "string",
            "enum": [
              "carton",
              "pallet"
            ]
          },
          "from": {
            "type": "integer",
            "minimum": 1
          },
          "to": {
            "type": "integer",
            "minimum": 1
          },
          "cartons": {
            "type": "integer",
            "minimum": 1
          },
          "template_version": {
            "type": "integer",
            "minimum": 0
          },
          "printed_by": {
            "type": "string"
          },
          "printed_at": {
            "type": "number"
          }
        }
      },
      "Consignee": {
        "type": "object",
        "additionalProperties": false,
        "description": "The immediate subsequent recipient of a shipment (#153; Circular 17/2021 Art. 6, Regulation (EC) 178/2002 Art. 18, FSMA 204). Staff-only: never on a public page or document.",
        "required": [
          "name",
          "address",
          "country",
          "gln",
          "registration_id"
        ],
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Legal name."
          },
          "address": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Postal address; line breaks allowed."
          },
          "country": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "ISO 3166-1 alpha-2 (an assigned code)."
          },
          "gln": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{13}$",
            "description": "GS1 Global Location Number with a valid check digit."
          },
          "registration_id": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[A-Za-z0-9][A-Za-z0-9 ./_-]{0,63}$",
            "description": "Tax or importer registration id."
          }
        }
      },
      "ConsigneeInput": {
        "type": "object",
        "additionalProperties": false,
        "description": "A consignee as written: `gln` and `registration_id` are optional.",
        "required": [
          "name",
          "address",
          "country"
        ],
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Legal name."
          },
          "address": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Postal address; line breaks allowed."
          },
          "country": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "ISO 3166-1 alpha-2 (an assigned code)."
          },
          "gln": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{13}$",
            "description": "GS1 Global Location Number with a valid check digit."
          },
          "registration_id": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[A-Za-z0-9][A-Za-z0-9 ./_-]{0,63}$",
            "description": "Tax or importer registration id."
          }
        }
      },
      "ShipmentConsigneeSet": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "consignee"
        ],
        "properties": {
          "consignee": {
            "$ref": "#/components/schemas/ConsigneeInput"
          },
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Required once the shipment departed (the change is kept as an amendment); accepted and not kept before."
          }
        }
      },
      "ShipmentDocumentInput": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "type",
          "number",
          "issued_on"
        ],
        "properties": {
          "type": {
            "type": "string",
            "enum": [
              "phytosanitary_certificate",
              "certificate_of_origin",
              "commercial_invoice",
              "packing_list",
              "customs_declaration",
              "bill_of_lading",
              "air_waybill",
              "test_report",
              "other"
            ]
          },
          "number": {
            "type": "string",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9 ./_-]{0,63}$"
          },
          "issued_on": {
            "type": "string",
            "format": "date",
            "description": "YYYY-MM-DD, from 2000-01-01 to tomorrow (Asia/Ho_Chi_Minh)."
          },
          "attachment_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "A PDF the tenant uploaded (PUT /v1/attachments/{sha256}); staff-only."
          }
        }
      },
      "ShipmentDocumentsSet": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "documents"
        ],
        "properties": {
          "documents": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/ShipmentDocumentInput"
            },
            "description": "The whole list, each (type, number) once; it replaces the stored one."
          },
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Required once the shipment departed (the change is kept as an amendment); accepted and not kept before."
          }
        }
      },
      "ShipmentDocument": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "type",
          "number",
          "issued_on",
          "attachment_sha256",
          "added_by",
          "added_at"
        ],
        "properties": {
          "type": {
            "type": "string",
            "enum": [
              "phytosanitary_certificate",
              "certificate_of_origin",
              "commercial_invoice",
              "packing_list",
              "customs_declaration",
              "bill_of_lading",
              "air_waybill",
              "test_report",
              "other"
            ]
          },
          "number": {
            "type": "string"
          },
          "issued_on": {
            "type": "string",
            "format": "date"
          },
          "attachment_sha256": {
            "type": [
              "string",
              "null"
            ]
          },
          "added_by": {
            "type": "string"
          },
          "added_at": {
            "type": "number"
          }
        }
      },
      "ShipmentPaperwork": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "required",
          "missing",
          "complete"
        ],
        "description": "The destination market's paperwork rule (CN: the consignee, the phytosanitary certificate and the test report) and what is still missing. The departure is refused (409 `missing_paperwork`) while anything is missing.",
        "properties": {
          "required": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "missing": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "complete": {
            "type": "boolean"
          }
        }
      },
      "ShipmentAmendment": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "kind",
          "reason",
          "before",
          "after",
          "amended_by",
          "amended_at"
        ],
        "description": "A change made after the departure: the consignee or the document list before and after it.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "kind": {
            "type": "string",
            "enum": [
              "consignee",
              "documents"
            ]
          },
          "reason": {
            "type": "string"
          },
          "before": {
            "description": "The consignee (or null) or the document list before the change."
          },
          "after": {
            "description": "The consignee or the document list after the change."
          },
          "amended_by": {
            "type": "string"
          },
          "amended_at": {
            "type": "number"
          }
        }
      },
      "HarvestKey": {
        "type": "object",
        "description": "#160: a harvest app install's request to sign harvest records with its own key. The private key is a non-extractable WebCrypto ECDSA P-256 key that never leaves the browser; the public key's PEM is never returned. `kid` and `device_id` derive from `fingerprint_sha256`, the SHA-256 of the key's SubjectPublicKeyInfo DER. Once approved, the device (profile `vn.agritrace.harvest-app`, site and facility `facility`) and its active key exist in the fleet, and the install sends its signed `harvest` envelopes to `POST /v1/ingest/{tenant}/{facility}/{device_id}/event/harvest`.",
        "required": [
          "kid",
          "device_id",
          "tenant",
          "facility",
          "label",
          "status",
          "fingerprint_sha256",
          "fingerprint",
          "requested_by",
          "requested_at",
          "decided_by",
          "decided_at",
          "revoked_at",
          "revoke_reason"
        ],
        "additionalProperties": false,
        "properties": {
          "kid": {
            "type": "string"
          },
          "device_id": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "facility": {
            "type": "string",
            "description": "The collection point the install records for."
          },
          "label": {
            "type": "string",
            "description": "A name people recognise the install by."
          },
          "status": {
            "enum": [
              "pending",
              "approved",
              "rejected",
              "revoked"
            ],
            "description": "`pending` until a tenant admin decides; `revoked` once the approved key was revoked (POST /v1/keys/{kid}/revoke). Rejected and revoked are final: the install makes a new key."
          },
          "fingerprint_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "fingerprint": {
            "type": "string",
            "description": "First four and last four hex characters."
          },
          "requested_by": {
            "type": "string"
          },
          "requested_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "decided_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "decided_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds."
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; set only when `status` is revoked."
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "rotation",
              "compromise",
              null
            ]
          }
        },
        "example": {
          "kid": "harvest-19fcfa6012e7f761a1f1e408:k1",
          "device_id": "harvest-19fcfa6012e7f761a1f1e408",
          "tenant": "coop-dl",
          "facility": "VN-DL-PH-01",
          "label": "Weighing desk phone",
          "status": "pending",
          "fingerprint_sha256": "19fcfa6012e7f761a1f1e408e6bc08ce10ce6a4347be82fd3c9ddf6a9fcfe0d9",
          "fingerprint": "19fc…e0d9",
          "requested_by": "op@coop.example",
          "requested_at": 1790000000.5,
          "decided_by": null,
          "decided_at": null,
          "revoked_at": null,
          "revoke_reason": null
        }
      },
      "HarvestKeyPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/HarvestKey"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "HarvestKeyRegister": {
        "type": "object",
        "required": [
          "public_key_pem",
          "facility",
          "label"
        ],
        "additionalProperties": false,
        "properties": {
          "public_key_pem": {
            "type": "string",
            "maxLength": 1024,
            "description": "The install's EC P-256 public key as one PEM SubjectPublicKeyInfo block."
          },
          "facility": {
            "type": "string",
            "description": "A facility of the caller's tenant (within an operator's facilities)."
          },
          "label": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100
          }
        },
        "example": {
          "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n",
          "facility": "VN-DL-PH-01",
          "label": "Weighing desk phone"
        }
      },
      "CompanyProfileUpdate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "legal_name"
        ],
        "description": "The whole profile (a PUT replaces it: a field left out, null or blank is cleared). Text is trimmed and may not hold control characters. The logo is set with PUT /v1/company/logo.",
        "properties": {
          "legal_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "As on the business registration. Required; trimmed, not blank."
          },
          "trading_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "address": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 300
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "In Viet Nam (`country` VN): deprecated (#273), sunset 1 May 2027; send `province_code` and `commune_code` instead (with them this must be absent or null), and a profile given as text only is stored as not yet coded and answered with the `Deprecation`, `Sunset` and `Link` headers. Deprecated in Viet Nam only: in another country this stays the free-text region and is not deprecated.",
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "District or commune. In Viet Nam (`country` VN): deprecated (#273), sunset 1 May 2027; Viet Nam has had no district level since 1 July 2025, so send `province_code` and `commune_code` instead (with them this must be absent or null, 400 `district_with_codes`). Deprecated in Viet Nam only: in another country this stays the free-text locality and is not deprecated.",
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100,
              "description": "District or commune."
            }
          },
          "province_code": {
            "description": "#273: the province (tỉnh or thành phố trực thuộc trung ương) by its official 2-digit code in the administrative units list in force (`getAdminUnits`). Sent with `commune_code`, both or neither; with them `province`, `district` and `commune` must be absent or null and the server writes the official names. Only for an address in Viet Nam (`country` VN or absent): with another country the codes are refused (400 `invalid_country`) and `province` and `district` stay free text.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "#273: the commune (xã, phường or đặc khu) by its official 5-digit code in the administrative units list in force (`getAdminUnits` with `province`). Sent with `province_code`, both or neither; the commune must lie in that province by the list, never by its digits.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "country": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[A-Z]{2}$",
            "description": "ISO 3166-1 alpha-2 code in capital letters; null or absent: VN."
          },
          "tax_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 32,
            "description": "Tax or business registration number. At most 32 characters for every country; the Vietnamese format is not checked yet (the exact rule awaits the owner's confirmation, #186)."
          },
          "contact_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "contact_phone": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 32,
            "description": "Digits, spaces and + ( ) . - only, starting with + or a digit."
          },
          "contact_email": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 254,
            "description": "An email address (name@domain.tld)."
          },
          "website": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "An https:// address with a DNS host name; no user name or password."
          }
        },
        "example": {
          "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
          "trading_name": "Durian DL",
          "address": "12 Nguyễn Tất Thành",
          "province": "Đắk Lắk",
          "district": "Buôn Ma Thuột",
          "country": "VN",
          "tax_id": "6001234567",
          "contact_name": "Nguyễn Văn A",
          "contact_phone": "+84 912 345 678",
          "contact_email": "a.nguyen@coop.example",
          "website": "https://coop.example"
        }
      },
      "CompanyLogo": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "sha256",
          "media_type",
          "size"
        ],
        "properties": {
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "media_type": {
            "type": "string",
            "enum": [
              "image/png",
              "image/jpeg"
            ]
          },
          "size": {
            "type": "integer",
            "minimum": 1,
            "maximum": 262144
          }
        },
        "description": "The logo as stored: a PNG or JPEG the company uploaded (an attachment of the company)."
      },
      "CompanyProfile": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "tenant",
          "name",
          "legal_name",
          "trading_name",
          "address",
          "province",
          "district",
          "country",
          "tax_id",
          "contact_name",
          "contact_phone",
          "contact_email",
          "website",
          "logo",
          "updated_at",
          "updated_by"
        ],
        "description": "The selected company's legal identity. Every field is null until set (country: VN). Changing it never changes a sealed lot: sealed facts and signed credentials keep what they recorded.",
        "properties": {
          "tenant": {
            "type": "string",
            "description": "The company's id (X-Tenant)."
          },
          "name": {
            "type": "string",
            "description": "The company's short display name (tenants.name), unchanged by the profile."
          },
          "legal_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "trading_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "address": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 300
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "country": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "VN until set."
          },
          "tax_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 32
          },
          "contact_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "contact_phone": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 32
          },
          "contact_email": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 254
          },
          "website": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "logo": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/CompanyLogo"
              },
              {
                "type": "null"
              }
            ]
          },
          "updated_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Seconds since the epoch; null until the profile is first saved."
          },
          "updated_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who saved it last; null until then."
          },
          "commune": {
            "description": "The commune's official name (xã, phường or đặc khu) when the record is coded; else null. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "x-not-in-sdk": true
          },
          "province_code": {
            "description": "The province's official 2-digit code, in the list `admin_units_version`; null when not coded. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "The commune's official 5-digit code, in the list `admin_units_version`; null when not coded. A code is only meaningful with its version (codes were reused across the 2025 reform). Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "admin_units_version": {
            "description": "The version of the official list the codes were taken from (for example `vn-2026-10-17`); null without codes. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^vn-[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "address_before_reform": {
            "description": "The province, district and commune text the record held before it was coded, or the text a request gave through the deprecated text path; kept for good once set. Null for a record entered with codes. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "province",
              "district",
              "commune"
            ],
            "properties": {
              "province": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "district": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "commune": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "x-not-in-sdk": true
          },
          "address_status": {
            "description": "`coded`: the codes are set from the official list; `choose_commune`: the old commune was split, a person picks one of `address_candidates`; `needs_commune`: no codes yet (given as text, or before the reform), a person picks the commune; `outside_vietnam`: a company profile in another country, where the codes do not apply. Null for a record not reviewed since the codes were introduced. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "coded",
              "choose_commune",
              "needs_commune",
              "outside_vietnam",
              null
            ],
            "x-not-in-sdk": true
          },
          "address_candidates": {
            "description": "For `choose_commune`: the official commune codes to pick from; else null. Only with `admin_units=1` on the read (#273); never in a write's answer nor without the parameter.",
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string",
              "pattern": "^[0-9]{5}$"
            },
            "x-not-in-sdk": true
          }
        },
        "example": {
          "tenant": "coop-dl",
          "name": "Coop DL",
          "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
          "trading_name": "Durian DL",
          "address": "12 Nguyễn Tất Thành",
          "province": "Đắk Lắk",
          "district": "Buôn Ma Thuột",
          "country": "VN",
          "tax_id": "6001234567",
          "contact_name": "Nguyễn Văn A",
          "contact_phone": "+84 912 345 678",
          "contact_email": "a.nguyen@coop.example",
          "website": "https://coop.example",
          "logo": {
            "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
            "media_type": "image/png",
            "size": 20480
          },
          "updated_at": 1791000000.0,
          "updated_by": "admin@coop.example"
        }
      },
      "CompanyProducer": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "legal_name",
          "address",
          "district",
          "province",
          "country"
        ],
        "description": "#186 (SELF-1-5): the lot's producer as its company profile names it now: the legal name and the address lines, never the trading name, tax number, contacts or website. Read when the label or dossier is built, so it is not part of any seal.",
        "properties": {
          "legal_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "address": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 300
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "District or commune."
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100
          },
          "country": {
            "type": "string",
            "pattern": "^[A-Z]{2}$",
            "description": "ISO 3166-1 alpha-2; VN until set."
          },
          "commune": {
            "description": "#273: the company's commune (official name) when its profile is coded; null otherwise, and null for a household business that has not opted in to its full address. Only with `admin_units=1`, in getCompanyPublicIdentity's `public_producer` and in getLotExportLabel's `producer`; never in a customs dossier or without the parameter.",
            "type": [
              "string",
              "null"
            ],
            "x-not-in-sdk": true
          }
        }
      },
      "CompanyPublicIdentity": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "household_business",
          "public_full_address",
          "public_legal_name",
          "public_producer"
        ],
        "description": "#208: how the company is named on public outputs (today the lot's public customs file).",
        "properties": {
          "household_business": {
            "type": "boolean",
            "description": "The company is a household business (hộ kinh doanh). Its public customs file then names it by its trading name (or 'Hộ kinh doanh' alone when it has no trading name, never its tax number) and shows its province only, unless it opts in below. False for a company."
          },
          "public_full_address": {
            "type": "boolean",
            "description": "A household business shows its full address (address and district too) on its public customs file. Always false for a company."
          },
          "public_legal_name": {
            "type": "boolean",
            "description": "A household business shows its legal name (a person's name) on its public customs file instead of its trading name. Always false for a company."
          },
          "public_producer": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/CompanyProducer"
              },
              {
                "type": "null"
              }
            ],
            "description": "The producer as the lot's public customs file shows it now: for a company its legal name and full address; for a household business its trading name (or 'Hộ kinh doanh' alone, never its tax number) in `legal_name` and its province only, unless it opted in. Null until the profile is saved."
          }
        },
        "example": {
          "household_business": false,
          "public_full_address": false,
          "public_legal_name": false,
          "public_producer": {
            "legal_name": "Hợp tác xã Sầu riêng Đắk Lắk",
            "address": "12 Nguyễn Tất Thành",
            "district": "Buôn Ma Thuột",
            "province": "Đắk Lắk",
            "country": "VN"
          }
        }
      },
      "CompanyPublicIdentityUpdate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "household_business",
          "public_full_address",
          "public_legal_name"
        ],
        "description": "#208: every flag, true or false. The opt-ins are stored false unless `household_business` is true.",
        "properties": {
          "household_business": {
            "type": "boolean",
            "description": "The company is a household business (hộ kinh doanh). Its public customs file then names it by its trading name (or 'Hộ kinh doanh' alone when it has no trading name, never its tax number) and shows its province only, unless it opts in below. False for a company."
          },
          "public_full_address": {
            "type": "boolean",
            "description": "A household business shows its full address (address and district too) on its public customs file. Always false for a company."
          },
          "public_legal_name": {
            "type": "boolean",
            "description": "A household business shows its legal name (a person's name) on its public customs file instead of its trading name. Always false for a company."
          }
        },
        "example": {
          "household_business": true,
          "public_full_address": false,
          "public_legal_name": false
        }
      },
      "CompanyLogoStored": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "sha256",
          "media_type",
          "size",
          "width",
          "height"
        ],
        "properties": {
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "media_type": {
            "type": "string",
            "enum": [
              "image/png",
              "image/jpeg"
            ]
          },
          "size": {
            "type": "integer",
            "minimum": 1,
            "maximum": 262144
          },
          "width": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1024
          },
          "height": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1024
          }
        },
        "example": {
          "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
          "media_type": "image/png",
          "size": 20480,
          "width": 512,
          "height": 256
        }
      },
      "TenantAdmin": {
        "type": "object",
        "required": [
          "user_id",
          "email",
          "display_name",
          "status"
        ],
        "additionalProperties": false,
        "properties": {
          "user_id": {
            "type": "integer"
          },
          "email": {
            "type": "string",
            "description": "The email the admin signs in with."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "enum": [
              "active",
              "disabled"
            ]
          }
        },
        "example": {
          "user_id": 4,
          "email": "boss@coop-new.example",
          "display_name": "Chi Lan",
          "status": "active"
        }
      },
      "TenantAdminList": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/TenantAdmin"
            }
          }
        }
      },
      "AdminInvitationCreate": {
        "type": "object",
        "required": [
          "email"
        ],
        "additionalProperties": false,
        "properties": {
          "email": {
            "type": "string",
            "maxLength": 320,
            "description": "The first admin's email: their sign-in name, not checked by any email."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "Proposed as the new account's name; the invitee may change it."
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 200,
            "description": "Why (one line). Required when the company already has an admin (admin recovery); written to the company's activity log."
          }
        },
        "example": {
          "email": "first.admin@coop-new.example",
          "display_name": "Chi Lan"
        }
      },
      "RecoveryLinkCreate": {
        "type": "object",
        "required": [
          "reason"
        ],
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Why (one line); written to the company's activity log."
          }
        },
        "example": {
          "reason": "Lost phone, cannot sign in"
        }
      },
      "AccountLinkCreated": {
        "type": "object",
        "required": [
          "id",
          "link",
          "expires_at",
          "emailed"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer"
          },
          "link": {
            "type": "string",
            "description": "The link, shown this once: the token is in the URL fragment (`/login#invite=...` or `/login#reset=...`), so it never reaches a server log. Only its SHA-256 is stored."
          },
          "expires_at": {
            "type": "number",
            "description": "Unix seconds: 72 hours after creation for an invitation, 24 hours for a recovery link."
          },
          "emailed": {
            "type": "boolean",
            "description": "#270. Whether CropPath queued this link's email to its person. False when this server sends no email, or when it cannot email this address (one SMTP cannot carry): the link must then be passed on by hand.",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "id": 12,
          "link": "https://txng.theio.vn/login#invite=agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
          "expires_at": 1790259200.5,
          "emailed": true
        },
        "x-sdk-example": {
          "id": 12,
          "link": "https://txng.theio.vn/login#invite=agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
          "expires_at": 1790259200.5
        }
      },
      "AccountLinkToken": {
        "type": "object",
        "required": [
          "token"
        ],
        "additionalProperties": false,
        "properties": {
          "token": {
            "type": "string",
            "description": "The token from the link's fragment."
          }
        },
        "example": {
          "token": "agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl"
        }
      },
      "AccountLinkInfo": {
        "type": "object",
        "required": [
          "purpose",
          "company",
          "role",
          "email",
          "expires_at",
          "account_exists"
        ],
        "additionalProperties": false,
        "properties": {
          "purpose": {
            "enum": [
              "invite",
              "reset",
              "admin_recovery"
            ]
          },
          "company": {
            "type": "string",
            "description": "The company's name."
          },
          "role": {
            "enum": [
              "tenant_admin",
              "operator",
              "auditor",
              "lab",
              "agronomist"
            ],
            "x-sdk-enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "email": {
            "type": "string",
            "description": "The account's email; it cannot be changed on the page."
          },
          "expires_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "account_exists": {
            "type": "boolean",
            "description": "Whether the email already has a CropPath account: the invitee then signs in with that account's password instead of choosing one."
          }
        },
        "example": {
          "purpose": "invite",
          "company": "New Coop",
          "role": "tenant_admin",
          "email": "first.admin@coop-new.example",
          "expires_at": 1790259200.5,
          "account_exists": false
        }
      },
      "AccountLinkAccept": {
        "type": "object",
        "required": [
          "token",
          "password"
        ],
        "additionalProperties": false,
        "properties": {
          "token": {
            "type": "string"
          },
          "password": {
            "type": "string",
            "description": "A new account's or a reset's new password (12 to 1,024 characters); for an email that already has an account, that account's password."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "A new account's name; ignored for an existing account."
          }
        },
        "example": {
          "token": "agi_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGxl",
          "password": "correct horse battery",
          "display_name": "Chi Lan"
        }
      },
      "Member": {
        "type": "object",
        "description": "SELF-1-4 (#185). Someone who belongs to the company. Never a password, a token or a session.",
        "required": [
          "user_id",
          "email",
          "display_name",
          "role",
          "facilities",
          "other_roles",
          "lab_id",
          "status",
          "account_status",
          "last_sign_in_at",
          "joined_at",
          "two_factor",
          "locked"
        ],
        "additionalProperties": false,
        "properties": {
          "user_id": {
            "type": "integer"
          },
          "email": {
            "type": "string",
            "description": "The email the person signs in with."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "role": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "tenant_admin",
              "operator",
              "auditor",
              "agronomist",
              null
            ],
            "description": "The member's role in this company; null when the person holds only platform-managed roles here (a lab user).",
            "x-sdk-enum": [
              "tenant_admin",
              "operator",
              "auditor",
              null
            ]
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "An operator's facility codes; null = every facility of the company (always null for another role)."
          },
          "other_roles": {
            "type": "array",
            "items": {
              "enum": [
                "lab",
                "platform_admin"
              ]
            },
            "description": "Platform-managed roles held in this company: shown, never changed here."
          },
          "lab_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The lab of a lab membership."
          },
          "status": {
            "enum": [
              "active",
              "disabled"
            ],
            "description": "`disabled`: turned off for this company (the person keeps every other company)."
          },
          "account_status": {
            "enum": [
              "active",
              "disabled"
            ],
            "description": "The account itself, managed by CropPath only."
          },
          "last_sign_in_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the newest session CropPath still keeps (sessions are deleted 30 days after they end); null: none in that time."
          },
          "joined_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null for a membership older than #184."
          },
          "two_factor": {
            "type": "boolean",
            "description": "SELF-1-6 (#187): the member's two-step sign-in is on."
          },
          "locked": {
            "type": "boolean",
            "description": "SELF-2-10 (#199): the member is locked out of signing in now (too many wrong passwords or two-step codes; the lock ends by itself after 15 minutes or when a company admin unlocks it). Never how many failures they had."
          }
        },
        "example": {
          "user_id": 7,
          "email": "lan@coop-dl.example",
          "display_name": "Chi Lan",
          "role": "operator",
          "facilities": [
            "VN-TGPH-021"
          ],
          "other_roles": [],
          "lab_id": null,
          "status": "active",
          "account_status": "active",
          "last_sign_in_at": 1790086400.5,
          "joined_at": 1789000000.0,
          "two_factor": false,
          "locked": false
        }
      },
      "MemberList": {
        "type": "object",
        "required": [
          "items",
          "active_admins"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Member"
            }
          },
          "active_admins": {
            "type": "integer",
            "description": "How many company admins are active, with an active account (the last-admin rule)."
          }
        },
        "example": {
          "items": [
            {
              "user_id": 7,
              "email": "lan@coop-dl.example",
              "display_name": "Chi Lan",
              "role": "operator",
              "facilities": [
                "VN-TGPH-021"
              ],
              "other_roles": [],
              "lab_id": null,
              "status": "active",
              "account_status": "active",
              "last_sign_in_at": 1790086400.5,
              "joined_at": 1789000000.0,
              "two_factor": false,
              "locked": false
            }
          ],
          "active_admins": 1
        }
      },
      "MemberUpdate": {
        "type": "object",
        "required": [
          "role"
        ],
        "additionalProperties": false,
        "properties": {
          "role": {
            "enum": [
              "tenant_admin",
              "operator",
              "auditor",
              "agronomist"
            ],
            "x-sdk-enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "Operators only: codes of the company's facilities; null or an empty list = every facility."
          }
        },
        "example": {
          "role": "operator",
          "facilities": [
            "VN-TGPH-021"
          ]
        }
      },
      "InvitationCreate": {
        "type": "object",
        "required": [
          "email",
          "role"
        ],
        "additionalProperties": false,
        "properties": {
          "email": {
            "type": "string",
            "maxLength": 320,
            "description": "The email the person will sign in with."
          },
          "role": {
            "enum": [
              "tenant_admin",
              "operator",
              "auditor",
              "agronomist"
            ],
            "x-sdk-enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "Operators only: codes of the company's facilities; null or an empty list = every facility."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          }
        },
        "example": {
          "email": "new.colleague@coop-dl.example",
          "role": "operator",
          "facilities": null,
          "display_name": "Anh Minh"
        }
      },
      "Invitation": {
        "type": "object",
        "description": "SELF-1-4 (#185). An invitation link or a password link of the company; never the link or its token.",
        "required": [
          "id",
          "purpose",
          "email",
          "role",
          "facilities",
          "display_name",
          "status",
          "created_by",
          "created_at",
          "expires_at",
          "used_at",
          "used_by",
          "revoked_at",
          "revoked_by"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer"
          },
          "purpose": {
            "enum": [
              "invite",
              "reset"
            ],
            "description": "invite: an invitation to join the company; reset: a password link for a member (`email` and `role` are that member's)."
          },
          "email": {
            "type": "string"
          },
          "role": {
            "enum": [
              "tenant_admin",
              "operator",
              "auditor",
              "agronomist"
            ],
            "x-sdk-enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "An operator's facility codes; null = every facility of the company (always null for another role)."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "status": {
            "enum": [
              "pending",
              "used",
              "expired",
              "revoked"
            ],
            "description": "pending: works until `expires_at`; used: accepted (`used_at`, `used_by`); revoked; expired."
          },
          "created_by": {
            "type": "string",
            "description": "Who created it (an email, or `cli:<user>`)."
          },
          "created_at": {
            "type": "number"
          },
          "expires_at": {
            "type": "number"
          },
          "used_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "used_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "id": 12,
          "purpose": "invite",
          "email": "new.colleague@coop-dl.example",
          "role": "operator",
          "facilities": null,
          "display_name": "Anh Minh",
          "status": "pending",
          "created_by": "boss@coop-dl.example",
          "created_at": 1790000000.0,
          "expires_at": 1790259200.0,
          "used_at": null,
          "used_by": null,
          "revoked_at": null,
          "revoked_by": null
        }
      },
      "InvitationList": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Invitation"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 12,
              "purpose": "invite",
              "email": "new.colleague@coop-dl.example",
              "role": "operator",
              "facilities": null,
              "display_name": "Anh Minh",
              "status": "pending",
              "created_by": "boss@coop-dl.example",
              "created_at": 1790000000.0,
              "expires_at": 1790259200.0,
              "used_at": null,
              "used_by": null,
              "revoked_at": null,
              "revoked_by": null
            }
          ],
          "next_cursor": null
        }
      },
      "InvitationRevoked": {
        "type": "object",
        "required": [
          "id",
          "status"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer"
          },
          "status": {
            "enum": [
              "revoked"
            ]
          }
        },
        "example": {
          "id": 12,
          "status": "revoked"
        }
      },
      "TwoFactorState": {
        "type": "object",
        "description": "SELF-1-6 (#187). The signed-in user's own two-step sign-in. Never the secret or a code.",
        "required": [
          "enabled",
          "backup_codes_left",
          "verified",
          "required",
          "deadline"
        ],
        "additionalProperties": false,
        "properties": {
          "enabled": {
            "type": "boolean",
            "description": "The authenticator app is on for this account."
          },
          "backup_codes_left": {
            "type": "integer",
            "minimum": 0,
            "description": "Unused backup codes (0 when the app is off)."
          },
          "verified": {
            "type": "boolean",
            "description": "This session proved a second factor (a code at sign-in, at re-authentication or when the app was turned on)."
          },
          "required": {
            "type": "boolean",
            "description": "This account must use two-step sign-in when acting for the selected company (a platform admin; a company admin after the deadline; a member of a company that requires it). When it is true and `verified` is false, every company route answers 403 `two_factor_required` and the console shows the setup screen."
          },
          "deadline": {
            "type": [
              "number",
              "null"
            ],
            "description": "For a company admin before the deadline: the Unix time from which two-step sign-in is required (the console prompts until then); null otherwise."
          }
        },
        "example": {
          "enabled": true,
          "backup_codes_left": 9,
          "verified": true,
          "required": false,
          "deadline": null
        }
      },
      "SecondFactorChallenge": {
        "type": "object",
        "description": "SELF-1-6 (#187). The password was right and the account has two-step sign-in: no session yet. Send `ticket` with a code to POST /v1/auth/login/second-factor before `expires_at`.",
        "required": [
          "second_factor",
          "ticket",
          "expires_at"
        ],
        "additionalProperties": false,
        "properties": {
          "second_factor": {
            "enum": [
              "required"
            ]
          },
          "ticket": {
            "type": "string",
            "description": "32 random bytes (base64url), valid 5 minutes, for one sign-in and at most 5 codes. Only its SHA-256 is stored."
          },
          "expires_at": {
            "type": "number",
            "description": "Unix seconds."
          }
        },
        "example": {
          "second_factor": "required",
          "ticket": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGl2",
          "expires_at": 1790086700.0
        }
      },
      "SecondFactorLogin": {
        "type": "object",
        "required": [
          "ticket"
        ],
        "additionalProperties": false,
        "properties": {
          "ticket": {
            "type": "string",
            "minLength": 1
          },
          "code": {
            "type": "string",
            "description": "The 6-digit code from the authenticator app (spaces allowed)."
          },
          "backup_code": {
            "type": "string",
            "description": "One unused backup code instead (any case, spaces and hyphens allowed)."
          }
        },
        "example": {
          "ticket": "3q2-7wAAAAAB8kY0T3QxZ2dQbW5oS2Q1cHJ0eWFjdGl2",
          "code": "492039"
        }
      },
      "SecondFactorSession": {
        "type": "object",
        "description": "SELF-1-6 (#187). A session opened by the code step: the AuthSession fields plus what proved the second factor.",
        "required": [
          "user",
          "memberships",
          "csrf_token",
          "second_factor",
          "backup_codes_left"
        ],
        "additionalProperties": false,
        "properties": {
          "user": {
            "$ref": "#/components/schemas/User"
          },
          "memberships": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Membership"
            }
          },
          "csrf_token": {
            "type": "string"
          },
          "two_factor": {
            "$ref": "#/components/schemas/TwoFactorState"
          },
          "second_factor": {
            "enum": [
              "code",
              "backup_code"
            ],
            "description": "What proved the second factor."
          },
          "backup_codes_left": {
            "type": "integer",
            "minimum": 0,
            "description": "Unused backup codes left (tell the user when it runs low)."
          }
        },
        "example": {
          "user": {
            "id": 1,
            "email": "alice@coop.example",
            "display_name": "Alice"
          },
          "memberships": [
            {
              "tenant": "coop-dl",
              "role": "tenant_admin",
              "facilities": null,
              "lab_id": null
            }
          ],
          "csrf_token": "q3Vb0mXl2sQ",
          "second_factor": "code",
          "backup_codes_left": 10
        }
      },
      "TwoFactorSetup": {
        "type": "object",
        "description": "SELF-1-6 (#187). A new secret for the authenticator app, in this response only: show `otpauth_uri` as a QR code (never log it or send it anywhere else) and `secret` as text to type in.",
        "required": [
          "secret",
          "otpauth_uri",
          "issuer",
          "account",
          "digits",
          "period"
        ],
        "additionalProperties": false,
        "properties": {
          "secret": {
            "type": "string",
            "pattern": "^[A-Z2-7]{32}$",
            "description": "160 random bits in base32 (RFC 4648, no padding)."
          },
          "otpauth_uri": {
            "type": "string",
            "description": "otpauth://totp/CropPath:<email>?secret=...&issuer=CropPath"
          },
          "issuer": {
            "const": "CropPath"
          },
          "account": {
            "type": "string"
          },
          "digits": {
            "const": 6
          },
          "period": {
            "const": 30
          }
        },
        "example": {
          "secret": "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP",
          "otpauth_uri": "otpauth://totp/CropPath:alice@coop.example?secret=JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP&issuer=CropPath",
          "issuer": "CropPath",
          "account": "alice@coop.example",
          "digits": 6,
          "period": 30
        }
      },
      "TwoFactorCode": {
        "type": "object",
        "required": [
          "code"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string",
            "minLength": 1,
            "description": "The 6-digit code the app shows now."
          }
        },
        "example": {
          "code": "492039"
        }
      },
      "BackupCodes": {
        "type": "object",
        "description": "SELF-1-6 (#187). Ten single-use backup codes (80 random bits each, base32, grouped by four for reading aloud), in this response only; CropPath keeps only slow hashes of them.",
        "required": [
          "backup_codes"
        ],
        "additionalProperties": false,
        "properties": {
          "backup_codes": {
            "type": "array",
            "minItems": 10,
            "maxItems": 10,
            "items": {
              "type": "string",
              "pattern": "^[a-z2-7]{4}(-[a-z2-7]{4}){3}$"
            }
          }
        },
        "example": {
          "backup_codes": [
            "k3xq-7mfa-2pzd-q4ve",
            "a7hn-35sk-wqzr-t2bm",
            "uj4c-6pde-mb3x-7fkr",
            "q2wv-zyt5-4hna-kcpe",
            "n6ft-rm3a-x7qd-s5bj",
            "e4pk-2wvc-hy6m-zr3t",
            "c5ad-kqmx-7nrj-w2ze",
            "t3vy-hb6q-p4sm-x5ka",
            "z7rm-e2nk-4bhp-dq6w",
            "m5jd-ws3t-q7ac-2kyn"
          ]
        }
      },
      "TwoFactorDisable": {
        "type": "object",
        "required": [
          "password"
        ],
        "additionalProperties": false,
        "properties": {
          "password": {
            "type": "string",
            "minLength": 1
          },
          "code": {
            "type": "string",
            "description": "The 6-digit code from the app; or send `backup_code`."
          },
          "backup_code": {
            "type": "string"
          },
          "set_up_again": {
            "type": "boolean",
            "default": false,
            "description": "Turning it off to set the app up again at once (a new phone): allowed even when the account must use two-step sign-in."
          }
        },
        "example": {
          "password": "correct horse battery",
          "code": "492039"
        }
      },
      "CompanySecurity": {
        "type": "object",
        "description": "SELF-1-6 (#187). The selected company's sign-in rule and how many of its active members have two-step sign-in on.",
        "required": [
          "require_two_factor",
          "members",
          "members_with_two_factor",
          "admin_deadline",
          "updated_at",
          "updated_by"
        ],
        "additionalProperties": false,
        "properties": {
          "require_two_factor": {
            "type": "boolean",
            "description": "Every member must use two-step sign-in to act for this company."
          },
          "members": {
            "type": "integer",
            "minimum": 0,
            "description": "Active members (active membership and account)."
          },
          "members_with_two_factor": {
            "type": "integer",
            "minimum": 0
          },
          "admin_deadline": {
            "type": "number",
            "description": "Unix seconds from which every company admin must use two-step sign-in (60 days after the release that shipped it)."
          },
          "updated_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "updated_by": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "require_two_factor": true,
          "members": 12,
          "members_with_two_factor": 9,
          "admin_deadline": 1795270400.0,
          "updated_at": 1790086400.5,
          "updated_by": "admin@coop.example"
        }
      },
      "CompanySecurityUpdate": {
        "type": "object",
        "required": [
          "require_two_factor"
        ],
        "additionalProperties": false,
        "properties": {
          "require_two_factor": {
            "type": "boolean"
          }
        },
        "example": {
          "require_two_factor": true
        }
      },
      "TwoFactorReset": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Required from a platform admin (CropPath support): one line, kept in the company's activity log. Ignored for a company admin."
          }
        },
        "example": {
          "reason": "Lost phone, confirmed by Zalo call with the company director"
        }
      },
      "TwoFactorResetResult": {
        "type": "object",
        "required": [
          "user_id",
          "two_factor",
          "sessions_revoked"
        ],
        "additionalProperties": false,
        "properties": {
          "user_id": {
            "type": "integer"
          },
          "two_factor": {
            "const": false
          },
          "sessions_revoked": {
            "type": "integer",
            "minimum": 0,
            "description": "The member's sessions ended by the reset."
          }
        },
        "example": {
          "user_id": 7,
          "two_factor": false,
          "sessions_revoked": 1
        }
      },
      "MemberUnlockResult": {
        "type": "object",
        "description": "SELF-2-10 (#199). The member's sign-in lockout was cleared.",
        "required": [
          "user_id",
          "locked",
          "was_locked"
        ],
        "additionalProperties": false,
        "properties": {
          "user_id": {
            "type": "integer"
          },
          "locked": {
            "const": false
          },
          "was_locked": {
            "type": "boolean",
            "description": "The member was locked out when the request ran (false: there was nothing to clear but a count of earlier failures, which is cleared too). Never how many failures they had."
          }
        },
        "example": {
          "user_id": 7,
          "locked": false,
          "was_locked": true
        }
      },
      "OnboardingStep": {
        "type": "object",
        "description": "SELF-1-8 (#189). One step of the getting-started checklist, judged from the company's own records.",
        "required": [
          "id",
          "required",
          "status",
          "count",
          "total",
          "link"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string",
            "enum": [
              "profile",
              "second_admin",
              "admin_two_factor",
              "facility",
              "growing_areas",
              "operators",
              "issuer_keys",
              "devices",
              "first_lot",
              "first_sealed_lot",
              "first_label",
              "integrations"
            ],
            "description": "profile: the company profile holds a legal name, an address and a tax number (count of 3 filled). second_admin: at least two active company admins (count: admins). admin_two_factor: every active company admin has two-step sign-in on (count of total admins). facility: an approved facility (count approved of total; waiting_for_platform while none is approved; a company cannot create facilities in Phase 1). growing_areas: an approved growing area with a grower of the company (count approved of total areas; waiting_for_platform while every area with a grower is unapproved). operators: an active operator (count). issuer_keys: every approved facility has an active signing key (count of total approved facilities). devices: an active device seen within 7 days (count of total active devices). first_lot, first_sealed_lot: a lot, a sealed lot (count). first_label: a fruit or carton label printed or an export label print logged. integrations (optional): an active API token, API client or webhook (count)."
          },
          "required": {
            "type": "boolean",
            "description": "false for an optional step (integrations): the checklist is complete without it."
          },
          "status": {
            "type": "string",
            "enum": [
              "done",
              "to_do",
              "waiting_for_platform"
            ],
            "description": "waiting_for_platform: the company did its part and waits for CropPath (an approval)."
          },
          "count": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "description": "The number the step is judged by, where one helps."
          },
          "total": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "description": "What `count` is out of, where it applies."
          },
          "link": {
            "type": "string",
            "description": "The console screen (path and hash) where the step is done."
          }
        },
        "example": {
          "id": "facility",
          "required": true,
          "status": "waiting_for_platform",
          "count": 0,
          "total": 1,
          "link": "/admin/facilities"
        }
      },
      "Onboarding": {
        "type": "object",
        "description": "SELF-1-8 (#189). The selected company's getting-started checklist: every step computed from its own records, counts only. Only `hidden` is stored.",
        "required": [
          "tenant",
          "complete",
          "hidden",
          "hidden_at",
          "steps"
        ],
        "additionalProperties": false,
        "properties": {
          "tenant": {
            "type": "string"
          },
          "complete": {
            "type": "boolean",
            "description": "Every required step is done."
          },
          "hidden": {
            "type": "boolean",
            "description": "A company admin hid the checklist (the console then stops showing it on /admin)."
          },
          "hidden_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds when it was hidden; null while shown."
          },
          "steps": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OnboardingStep"
            },
            "description": "Every step, in the order a new company works through them."
          }
        },
        "example": {
          "tenant": "coop-dl",
          "complete": false,
          "hidden": false,
          "hidden_at": null,
          "steps": [
            {
              "id": "profile",
              "required": true,
              "status": "done",
              "count": 3,
              "total": 3,
              "link": "/admin/settings#profile"
            },
            {
              "id": "second_admin",
              "required": true,
              "status": "to_do",
              "count": 1,
              "total": null,
              "link": "/admin/settings#team"
            },
            {
              "id": "admin_two_factor",
              "required": true,
              "status": "to_do",
              "count": 0,
              "total": 1,
              "link": "/admin/settings#security"
            },
            {
              "id": "facility",
              "required": true,
              "status": "waiting_for_platform",
              "count": 0,
              "total": 1,
              "link": "/admin/facilities"
            },
            {
              "id": "growing_areas",
              "required": true,
              "status": "to_do",
              "count": 0,
              "total": 0,
              "link": "/admin/growing-areas"
            },
            {
              "id": "operators",
              "required": true,
              "status": "to_do",
              "count": 0,
              "total": null,
              "link": "/admin/settings#team"
            },
            {
              "id": "issuer_keys",
              "required": true,
              "status": "waiting_for_platform",
              "count": 0,
              "total": 0,
              "link": "/admin/settings/issuer-keys"
            },
            {
              "id": "devices",
              "required": true,
              "status": "to_do",
              "count": 0,
              "total": 0,
              "link": "/admin/devices"
            },
            {
              "id": "first_lot",
              "required": true,
              "status": "to_do",
              "count": 0,
              "total": null,
              "link": "/console/lots/new"
            },
            {
              "id": "first_sealed_lot",
              "required": true,
              "status": "to_do",
              "count": 0,
              "total": null,
              "link": "/console"
            },
            {
              "id": "first_label",
              "required": true,
              "status": "to_do",
              "count": null,
              "total": null,
              "link": "/console"
            },
            {
              "id": "integrations",
              "required": false,
              "status": "to_do",
              "count": 0,
              "total": null,
              "link": "/admin/settings/api-tokens"
            }
          ]
        }
      },
      "OnboardingUpdate": {
        "type": "object",
        "required": [
          "hidden"
        ],
        "additionalProperties": false,
        "properties": {
          "hidden": {
            "type": "boolean",
            "description": "true hides the checklist, false shows it again."
          }
        },
        "example": {
          "hidden": true
        }
      },
      "CompanyUsage": {
        "type": "object",
        "description": "SELF-2-5 (#194). The selected company's usage of its limits, its API calls per day, its quotas and what it stores (#134), counts only.",
        "required": [
          "tenant",
          "warn_percent",
          "limits",
          "api_calls",
          "quotas",
          "stored"
        ],
        "additionalProperties": false,
        "properties": {
          "tenant": {
            "type": "string"
          },
          "warn_percent": {
            "type": "integer",
            "description": "An entry warns from this percentage of its limit."
          },
          "limits": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CompanyUsageLimit"
            },
            "description": "Every limit, in a fixed order."
          },
          "api_calls": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CompanyApiCallDay"
            },
            "description": "The last 14 UTC days, newest first, today included (0 for a day without calls)."
          },
          "quotas": {
            "$ref": "#/components/schemas/CompanyUsageQuotas",
            "x-not-in-sdk": true
          },
          "stored": {
            "$ref": "#/components/schemas/CompanyUsageStored",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "tenant": "coop-dl",
          "warn_percent": 80,
          "limits": [
            {
              "id": "members",
              "used": 12,
              "limit": 200,
              "warning": false,
              "reached": false
            },
            {
              "id": "pending_links",
              "used": 2,
              "limit": 50,
              "warning": false,
              "reached": false
            },
            {
              "id": "devices",
              "used": 7,
              "limit": null,
              "warning": false,
              "reached": false
            },
            {
              "id": "api_tokens",
              "used": 3,
              "limit": 100,
              "warning": false,
              "reached": false
            },
            {
              "id": "api_clients",
              "used": 1,
              "limit": 50,
              "warning": false,
              "reached": false
            },
            {
              "id": "webhooks",
              "used": 17,
              "limit": 20,
              "warning": true,
              "reached": false
            }
          ],
          "api_calls": [
            {
              "day": "2026-10-11",
              "calls": 1520
            },
            {
              "day": "2026-10-10",
              "calls": 1873
            },
            {
              "day": "2026-10-09",
              "calls": 0
            }
          ],
          "quotas": {
            "api_per_minute": 1200,
            "api_per_day": 500000,
            "api_calls_today": 1520,
            "api_day_warning": false,
            "api_day_reached": false,
            "ingest_per_second": 100,
            "ingest_burst": 3000,
            "ingest_backlog": 0
          },
          "stored": {
            "envelopes": 184220,
            "scans": 52310,
            "attachments": 1730,
            "storage_bytes": 412876800
          }
        },
        "x-sdk-description": "SELF-2-5 (#194). The selected company's usage of its limits and its API calls per day, counts only.",
        "x-sdk-example": {
          "tenant": "coop-dl",
          "warn_percent": 80,
          "limits": [
            {
              "id": "members",
              "used": 12,
              "limit": 200,
              "warning": false,
              "reached": false
            },
            {
              "id": "pending_links",
              "used": 2,
              "limit": 50,
              "warning": false,
              "reached": false
            },
            {
              "id": "devices",
              "used": 7,
              "limit": null,
              "warning": false,
              "reached": false
            },
            {
              "id": "api_tokens",
              "used": 3,
              "limit": 100,
              "warning": false,
              "reached": false
            },
            {
              "id": "api_clients",
              "used": 1,
              "limit": 50,
              "warning": false,
              "reached": false
            },
            {
              "id": "webhooks",
              "used": 17,
              "limit": 20,
              "warning": true,
              "reached": false
            }
          ],
          "api_calls": [
            {
              "day": "2026-10-11",
              "calls": 1520
            },
            {
              "day": "2026-10-10",
              "calls": 1873
            },
            {
              "day": "2026-10-09",
              "calls": 0
            }
          ]
        }
      },
      "CompanyUsageLimit": {
        "type": "object",
        "description": "SELF-2-5 (#194). One per-company limit: what the company uses of it.",
        "required": [
          "id",
          "used",
          "limit",
          "warning",
          "reached"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string",
            "enum": [
              "members",
              "pending_links",
              "devices",
              "api_tokens",
              "api_clients",
              "webhooks"
            ],
            "description": "members: active members plus pending invitations (limit 200). pending_links: pending one-time links of every purpose, invitations and new-password links (limit 50). devices: active devices (no limit is enforced: `limit` null). api_tokens: live API tokens (limit 100). api_clients: live API clients (limit 50). webhooks: webhook subscriptions of every status (limit 20)."
          },
          "used": {
            "type": "integer",
            "minimum": 0
          },
          "limit": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "description": "The limit the backend enforces; null when there is none."
          },
          "warning": {
            "type": "boolean",
            "description": "`used` is at least `warn_percent` of `limit` (false without a limit)."
          },
          "reached": {
            "type": "boolean",
            "description": "`used` is at the limit: the next create is refused (false without a limit)."
          }
        },
        "example": {
          "id": "webhooks",
          "used": 17,
          "limit": 20,
          "warning": true,
          "reached": false
        }
      },
      "CompanyApiCallDay": {
        "type": "object",
        "description": "SELF-2-5 (#194). A company's API calls on one UTC day.",
        "required": [
          "day",
          "calls"
        ],
        "additionalProperties": false,
        "properties": {
          "day": {
            "type": "string",
            "format": "date",
            "description": "The UTC day, YYYY-MM-DD."
          },
          "calls": {
            "type": "integer",
            "minimum": 0
          }
        },
        "example": {
          "day": "2026-10-11",
          "calls": 1520
        }
      },
      "IntegrityAnchorTimestamp": {
        "description": "INTEGRITY-2 (#202): the RFC 3161 timestamp of an anchor (the anchor's 32 bytes are the message imprint, SHA-256). `pending` while the job has no verified token (the TSA unreachable, or a token that did not verify; it retries); `verified` once a token was verified against the configured trust store and stored, then final.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "status",
          "gen_time",
          "token"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "verified"
            ]
          },
          "gen_time": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "The token's genTime (UTC); null while pending."
          },
          "token": {
            "type": [
              "string",
              "null"
            ],
            "description": "Base64 of the TimeStampToken's DER (a CMS SignedData of a TSTInfo); null while pending. Check it with `openssl ts -verify -digest <anchor> -in token.der -token_in -CAfile <TSA root>`."
          }
        }
      },
      "IntegrityAnchor": {
        "description": "INTEGRITY-2 (#202): one closed UTC day's anchor. The day's records (audit log rows, evidence envelopes, lot seals, reviews, and the envelopes not accepted when the day was anchored) are hashed into one Merkle tree per kind (RFC 9162: leaf SHA-256(0x00 || record), node SHA-256(0x01 || left || right), empty SHA-256(\"\"), leaves in the order of their hash); `day_root` = SHA-256(0x02 || audit_root || evidence_root || seal_root || review_root || held_root); `anchor` = SHA-256(prev_anchor || day_root || day as ASCII || audit_count || evidence_count || seal_count || review_count || held_count, each count 8 bytes big-endian). The first day's `prev_anchor` is 64 zeros. The record encoding is /developers/downloads/integrity-anchors.md; /developers/downloads/verify_anchors.py recomputes it with the Python standard library. Written once, never changed.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "day",
          "seq",
          "version",
          "prev_anchor",
          "audit_root",
          "evidence_root",
          "seal_root",
          "review_root",
          "held_root",
          "day_root",
          "audit_count",
          "evidence_count",
          "seal_count",
          "review_count",
          "held_count",
          "anchor",
          "created_at",
          "timestamp"
        ],
        "properties": {
          "day": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The UTC day the records were written (YYYY-MM-DD)."
          },
          "seq": {
            "type": "integer",
            "minimum": 0,
            "description": "Position in the chain: 0 for the first anchored day, then one per day without gaps."
          },
          "version": {
            "type": "integer",
            "enum": [
              1
            ],
            "description": "The encoding version."
          },
          "prev_anchor": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "The previous day's `anchor` (64 zeros for seq 0)."
          },
          "audit_root": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Root of the day's activity log rows."
          },
          "evidence_root": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Root of the evidence envelopes received that day (accepted, quarantined or rejected after review)."
          },
          "seal_root": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Root of the lot seals made that day."
          },
          "review_root": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Root of the reviews made that day (a person's decision on a quarantined envelope) and of the envelopes a pack sent back to quarantine that day (decision `requarantine`)."
          },
          "held_root": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "Root of the day's envelopes that were not accepted when the day was anchored, each with that status. A later status must be that one, a lower one, or a review's outcome; an envelope a pack sent back to quarantine is accepted again only after an approve review later than that."
          },
          "day_root": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "audit_count": {
            "type": "integer",
            "minimum": 0
          },
          "evidence_count": {
            "type": "integer",
            "minimum": 0
          },
          "seal_count": {
            "type": "integer",
            "minimum": 0
          },
          "review_count": {
            "type": "integer",
            "minimum": 0
          },
          "held_count": {
            "type": "integer",
            "minimum": 0
          },
          "anchor": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the job computed the anchor (UTC)."
          },
          "timestamp": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/IntegrityAnchorTimestamp"
              },
              {
                "type": "null"
              }
            ],
            "description": "Null while no TSA is configured or the job has not queued the anchor yet."
          }
        },
        "example": {
          "day": "2026-10-08",
          "seq": 41,
          "version": 1,
          "prev_anchor": "be49fb23ac82b5ec39175d41c24be9962da541a3e6e3e942e065c9b1f85a977d",
          "audit_root": "69517c75b68faea3ae84cb5116c7d12125d32e23529a1ff6ef36f666ce0fd882",
          "evidence_root": "a59ba7faac45b5663de69c9050f21fc04ee99a39fba52cebc08003fc009b9b69",
          "seal_root": "b161f22a5c2003f3d72b16a782971049af1c3686cfa1395b65238616c7854c6d",
          "review_root": "7f2c1c56a4cbbd0d6e3c4f5c2b5d1b6a0f3e7a9c8d2e4b1f6a3c5d7e9f0b2a4c",
          "held_root": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
          "day_root": "ad8af655fbd5987cb1634e88fa4997bfd23f0e106632e639ec35c8195f4d9deb",
          "audit_count": 1840,
          "evidence_count": 9312,
          "seal_count": 3,
          "review_count": 2,
          "held_count": 0,
          "anchor": "b54619909ae9f243ff09bd33eeab7103c8979cc0a354952304c2e12580ccb899",
          "created_at": "2026-10-09T01:00:04Z",
          "timestamp": {
            "status": "verified",
            "gen_time": "2026-10-09T01:00:06Z",
            "token": "MIIGTwYJKoZIhvcNAQcCoIIGQDCCBjwCAQMxDzANBglghkgBZQMEAgEFADCB"
          }
        }
      },
      "IntegrityAnchorPage": {
        "description": "INTEGRITY-2 (#202): one page of anchors, oldest first.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "version",
          "genesis",
          "items",
          "next_after"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "enum": [
              1
            ]
          },
          "genesis": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "The `prev_anchor` of the first day: 64 zeros."
          },
          "items": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/IntegrityAnchor"
            }
          },
          "next_after": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `after` for the next page; null on the last page."
          }
        },
        "example": {
          "version": 1,
          "genesis": "0000000000000000000000000000000000000000000000000000000000000000",
          "items": [
            {
              "day": "2026-10-08",
              "seq": 41,
              "version": 1,
              "prev_anchor": "be49fb23ac82b5ec39175d41c24be9962da541a3e6e3e942e065c9b1f85a977d",
              "audit_root": "69517c75b68faea3ae84cb5116c7d12125d32e23529a1ff6ef36f666ce0fd882",
              "evidence_root": "a59ba7faac45b5663de69c9050f21fc04ee99a39fba52cebc08003fc009b9b69",
              "seal_root": "b161f22a5c2003f3d72b16a782971049af1c3686cfa1395b65238616c7854c6d",
              "review_root": "7f2c1c56a4cbbd0d6e3c4f5c2b5d1b6a0f3e7a9c8d2e4b1f6a3c5d7e9f0b2a4c",
              "held_root": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
              "day_root": "ad8af655fbd5987cb1634e88fa4997bfd23f0e106632e639ec35c8195f4d9deb",
              "audit_count": 1840,
              "evidence_count": 9312,
              "seal_count": 3,
              "review_count": 2,
              "held_count": 0,
              "anchor": "b54619909ae9f243ff09bd33eeab7103c8979cc0a354952304c2e12580ccb899",
              "created_at": "2026-10-09T01:00:04Z",
              "timestamp": {
                "status": "verified",
                "gen_time": "2026-10-09T01:00:06Z",
                "token": "MIIGTwYJKoZIhvcNAQcCoIIGQDCCBjwCAQMxDzANBglghkgBZQMEAgEFADCB"
              }
            }
          ],
          "next_after": null
        }
      },
      "AnchorInclusionProof": {
        "description": "INTEGRITY-2 (#202): the inclusion proof of one record in its day's anchor. Recompute the leaf from `record` (the canonical encoding of /developers/downloads/integrity-anchors.md), follow `path` (RFC 9162 section 2.1.3.2, leaf side first) to the anchor's root of `kind` (`seal_root` or `evidence_root`), then the anchor from its roots; compare the anchor with the one GET /v1/public/anchors publishes for `day` (/developers/downloads/verify_anchors.py `proof` does all of it). `included` is false when the record as stored today is not among the anchored ones (it was changed after its day was anchored); `path` is then empty.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "kind",
          "day",
          "record",
          "leaf_hash",
          "included",
          "leaf_index",
          "tree_size",
          "path",
          "anchor"
        ],
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "seal",
              "evidence"
            ]
          },
          "day": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "record": {
            "description": "The record's fields in encoding order: an AnchorSealRecord for `seal`, an AnchorEvidenceRecord for `evidence`.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/AnchorSealRecord"
              },
              {
                "$ref": "#/components/schemas/AnchorEvidenceRecord"
              }
            ]
          },
          "leaf_hash": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "included": {
            "type": "boolean"
          },
          "leaf_index": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0
          },
          "tree_size": {
            "type": "integer",
            "minimum": 0
          },
          "path": {
            "type": "array",
            "items": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$"
            }
          },
          "anchor": {
            "$ref": "#/components/schemas/IntegrityAnchor"
          }
        },
        "example": {
          "kind": "seal",
          "day": "2026-10-08",
          "record": {
            "manifest_sha256": "0000000000000000000000000000000000000000000000000000000000001efa",
            "sealed_at": 1791440400.25,
            "fruit_count": 13,
            "event_count": 41
          },
          "leaf_hash": "52b42e8bff3ec1d57e4813b951e084464611dd15d449f20ae82936fc7e1f70c2",
          "included": true,
          "leaf_index": 1,
          "tree_size": 3,
          "path": [
            "03c144ed8ca7f54eedbabe5204716a751defce4c61ad32756454df2d44cc6b06",
            "a9a8a7268b3840b423803a0ea58206e4eac69b1055a063a35b97ed5815705930"
          ],
          "anchor": {
            "day": "2026-10-08",
            "seq": 41,
            "version": 1,
            "prev_anchor": "be49fb23ac82b5ec39175d41c24be9962da541a3e6e3e942e065c9b1f85a977d",
            "audit_root": "69517c75b68faea3ae84cb5116c7d12125d32e23529a1ff6ef36f666ce0fd882",
            "evidence_root": "a59ba7faac45b5663de69c9050f21fc04ee99a39fba52cebc08003fc009b9b69",
            "seal_root": "b161f22a5c2003f3d72b16a782971049af1c3686cfa1395b65238616c7854c6d",
            "review_root": "7f2c1c56a4cbbd0d6e3c4f5c2b5d1b6a0f3e7a9c8d2e4b1f6a3c5d7e9f0b2a4c",
            "held_root": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "day_root": "ad8af655fbd5987cb1634e88fa4997bfd23f0e106632e639ec35c8195f4d9deb",
            "audit_count": 1840,
            "evidence_count": 9312,
            "seal_count": 3,
            "review_count": 2,
            "held_count": 0,
            "anchor": "b54619909ae9f243ff09bd33eeab7103c8979cc0a354952304c2e12580ccb899",
            "created_at": "2026-10-09T01:00:04Z",
            "timestamp": {
              "status": "verified",
              "gen_time": "2026-10-09T01:00:06Z",
              "token": "MIIGTwYJKoZIhvcNAQcCoIIGQDCCBjwCAQMxDzANBglghkgBZQMEAgEFADCB"
            }
          }
        }
      },
      "AnchorSealRecord": {
        "description": "INTEGRITY-2 (#202): a lot seal's record in its day's seal tree, fields in encoding order.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "manifest_sha256",
          "sealed_at",
          "fruit_count",
          "event_count"
        ],
        "properties": {
          "manifest_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "The seal's manifest hash, as the public lot record shows it."
          },
          "sealed_at": {
            "type": "number",
            "description": "Seal time, Unix seconds (encoded as binary64)."
          },
          "fruit_count": {
            "type": "integer",
            "minimum": 0
          },
          "event_count": {
            "type": "integer",
            "minimum": 0
          }
        },
        "example": {
          "manifest_sha256": "0000000000000000000000000000000000000000000000000000000000001efa",
          "sealed_at": 1791440400.25,
          "fruit_count": 13,
          "event_count": 41
        }
      },
      "AnchorEvidenceRecord": {
        "description": "INTEGRITY-2 (#202): an evidence envelope's record in its day's evidence tree, fields in encoding order. It names no device: the SHA-256 of the stored body commits to the device and its sequence number.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "received_at",
          "payload_sha256"
        ],
        "properties": {
          "id": {
            "type": "string",
            "description": "The envelope id (the EPCIS eventID without `urn:uuid:`)."
          },
          "received_at": {
            "type": "number",
            "description": "Reception time, Unix seconds (encoded as binary64)."
          },
          "payload_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the stored envelope body as UTF-8."
          }
        },
        "example": {
          "id": "9b2f6c1e-4d3a-4b8e-9f0a-1c2d3e4f5a6b",
          "received_at": 1791436805.5,
          "payload_sha256": "5d41402abc4b2a76b9719d911017c592ae2c2bd1fe1e9e4cd3d2f0ea8d8a1f3c"
        }
      },
      "DeviceApproval": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "keys"
        ],
        "properties": {
          "keys": {
            "type": "array",
            "maxItems": 100,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
            },
            "description": "The kids of the identity's waiting keys the platform admin saw in the queue (`keys` of its DeviceApprovalItem with approval `pending`), possibly none. Exactly these keys are approved; any other waiting key stays pending. 409 when one is no longer an active key of this device or gateway waiting for approval."
          }
        },
        "example": {
          "keys": [
            "knk-7-k2"
          ]
        }
      },
      "DeviceApprovalItem": {
        "type": "object",
        "description": "A device or gateway of any company in the platform's approval queue (#201). The pending queue also lists an approved one with an active key no platform admin approved yet.",
        "additionalProperties": false,
        "required": [
          "kind",
          "id",
          "tenant",
          "tenant_name",
          "site",
          "facility",
          "profile",
          "display_name",
          "registered_by",
          "registered_at",
          "approval",
          "approval_reason",
          "approval_at",
          "approval_by",
          "keys"
        ],
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "device",
              "gateway"
            ]
          },
          "id": {
            "type": "string",
            "description": "The device or gateway id (one namespace)."
          },
          "tenant": {
            "type": "string",
            "description": "The company that registered it."
          },
          "tenant_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "site": {
            "type": "string"
          },
          "facility": {
            "type": [
              "string",
              "null"
            ]
          },
          "profile": {
            "type": [
              "string",
              "null"
            ],
            "description": "The device profile; null for a gateway."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "registered_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who registered it (null before #201, or when the platform provisioned it)."
          },
          "registered_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null for an older gateway."
          },
          "approval": {
            "type": "string",
            "enum": [
              "pending",
              "approved",
              "rejected"
            ]
          },
          "approval_reason": {
            "type": [
              "string",
              "null"
            ]
          },
          "approval_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the last decision."
          },
          "approval_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who decided last: a platform admin, `provision` (the platform's seed) or `migration` (grandfathered when approval began)."
          },
          "keys": {
            "type": "array",
            "description": "Its active signing keys (never the public key itself), each with its own approval: a key a company registers after the device or gateway was approved waits for the platform; an approval lists the waiting keys it approves (DeviceApproval).",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "kid",
                "fingerprint",
                "fingerprint_sha256",
                "approval"
              ],
              "properties": {
                "kid": {
                  "type": "string"
                },
                "fingerprint": {
                  "type": "string",
                  "description": "Short form: first and last four hex digits."
                },
                "fingerprint_sha256": {
                  "type": "string",
                  "description": "SHA-256 of the key's DER, hex."
                },
                "approval": {
                  "type": "string",
                  "enum": [
                    "pending",
                    "approved"
                  ],
                  "description": "Only evidence signed with an approved key counts as Device-recorded or above."
                }
              }
            }
          }
        },
        "example": {
          "kind": "device",
          "id": "knk-7",
          "tenant": "coop-dl",
          "tenant_name": "Coop DL",
          "site": "ph1",
          "facility": "VN-TGPH-021",
          "profile": "vn.agritrace.durian-knocker",
          "display_name": "Line A2 knocker",
          "registered_by": "admin@coop.example",
          "registered_at": 1790000000.5,
          "approval": "pending",
          "approval_reason": null,
          "approval_at": null,
          "approval_by": null,
          "keys": [
            {
              "kid": "knk-7-k1",
              "fingerprint": "3f9a…c21e",
              "fingerprint_sha256": "3f9a00000000000000000000000000000000000000000000000000000000c21e",
              "approval": "pending"
            }
          ]
        }
      },
      "DeviceApprovalPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DeviceApprovalItem"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "Pass as `cursor` for the next page; null on the last page."
          }
        }
      },
      "DeviceRejection": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Shown to the company."
          }
        },
        "example": {
          "reason": "Serial number does not match the scale's calibration certificate."
        }
      },
      "PublicDeviceApproval": {
        "type": "object",
        "description": "#201: whether the devices whose evidence this step reads are approved by CropPath. `approved` false: evidence of a device CropPath has not approved is counted as Self-declared. `approved_on`: the local date of the latest approval, null when one was approved before approvals were recorded.",
        "additionalProperties": false,
        "required": [
          "approved",
          "approved_on"
        ],
        "properties": {
          "approved": {
            "type": "boolean"
          },
          "approved_on": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicIsoDate"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "PublicCorrections": {
        "description": "INTEGRITY-4 (#204): how often the journey steps of a public lot (or, for `measurement` on a fruit's page, the fruit) were corrected before the lot's seal. Counts and local dates only.",
        "type": "object",
        "additionalProperties": false,
        "required": [
          "sealed",
          "public_since",
          "steps"
        ],
        "properties": {
          "sealed": {
            "type": "boolean",
            "description": "The lot is sealed (closed, or later): no record of it can be corrected any more. False while it is open, when more corrections may follow."
          },
          "public_since": {
            "description": "The local date the lot was first public (its first measurement session opened); null when it has none.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/PublicIsoDate"
              },
              {
                "type": "null"
              }
            ]
          },
          "steps": {
            "type": "array",
            "maxItems": 4,
            "description": "One entry per step with at least one correction, in this order: registration, harvest, measurement, details.",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "kind",
                "count",
                "last_on",
                "after_public"
              ],
              "properties": {
                "kind": {
                  "type": "string",
                  "enum": [
                    "registration",
                    "harvest",
                    "measurement",
                    "details"
                  ],
                  "description": "The journey step corrected; `details`: the lot's own details (variety, product, GTIN), which no step shows."
                },
                "count": {
                  "type": "integer",
                  "minimum": 1,
                  "description": "How many corrections."
                },
                "last_on": {
                  "$ref": "#/components/schemas/PublicIsoDate"
                },
                "after_public": {
                  "type": "integer",
                  "minimum": 0,
                  "description": "How many of them came after the lot was first public (`public_since`), a `measurement` correction made while the fruit's own measurement session was running (not paused) left out."
                }
              }
            }
          }
        }
      },
      "ServerEpoch": {
        "type": "object",
        "description": "A signed server epoch value (SENS-B2c, #239). `sig` is over the canonical JSON of `epoch`, `issuedAt` and `kid`; `publicKeyJwk` is outside the signed part.",
        "required": [
          "epoch",
          "issuedAt",
          "kid",
          "sig",
          "publicKeyJwk"
        ],
        "additionalProperties": false,
        "properties": {
          "epoch": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$",
            "description": "The value a device cites in `context.epoch`: 128 random bits as lower-case hex."
          },
          "issuedAt": {
            "type": "string",
            "format": "date-time",
            "description": "When the server issued it (UTC, milliseconds)."
          },
          "kid": {
            "type": "string",
            "pattern": "^epoch-[0-9a-f]{16}$",
            "description": "The epoch key's id: `epoch-` and the first 16 hex digits of the SHA-256 of its public key (SubjectPublicKeyInfo DER)."
          },
          "sig": {
            "type": "object",
            "required": [
              "alg",
              "kid",
              "value"
            ],
            "additionalProperties": false,
            "properties": {
              "alg": {
                "const": "ES256"
              },
              "kid": {
                "type": "string",
                "pattern": "^epoch-[0-9a-f]{16}$"
              },
              "value": {
                "type": "string",
                "pattern": "^[A-Za-z0-9_-]{86}$",
                "description": "base64url of the 64-byte r || s."
              }
            }
          },
          "publicKeyJwk": {
            "$ref": "#/components/schemas/PublicJwk"
          }
        }
      },
      "PasswordRecoveryRequest": {
        "type": "object",
        "required": [
          "email",
          "backup_code",
          "new_password"
        ],
        "additionalProperties": false,
        "properties": {
          "email": {
            "type": "string",
            "minLength": 1,
            "description": "The email used to sign in."
          },
          "backup_code": {
            "type": "string",
            "minLength": 1,
            "description": "One unused backup code of the account (SELF-1-6, #187), as printed: any case, spaces and hyphens allowed."
          },
          "new_password": {
            "type": "string",
            "minLength": 12,
            "maxLength": 1024
          }
        },
        "example": {
          "email": "alice@coop.example",
          "backup_code": "abcd-efgh-ijkl-mnop",
          "new_password": "another long passphrase"
        }
      },
      "PasswordRecovered": {
        "type": "object",
        "required": [
          "backup_codes_left",
          "second_factor"
        ],
        "properties": {
          "backup_codes_left": {
            "type": "integer",
            "minimum": 0,
            "description": "The account's unused backup codes after this one."
          },
          "second_factor": {
            "type": "string",
            "enum": [
              "required"
            ],
            "description": "The next sign-in asks for the second step after the password."
          }
        },
        "example": {
          "backup_codes_left": 9,
          "second_factor": "required"
        }
      },
      "SignedInSession": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "browser",
          "os",
          "mobile",
          "created_at",
          "last_seen_at",
          "current"
        ],
        "description": "SELF-2-1 (#190). One live session of the signed-in user: what the browser told CropPath about itself, read into well-known names, and when it was opened and last used, to the minute. Never the session's token, its hash, its CSRF token, the client's IP address or the raw user agent.",
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1,
            "description": "The session's id: pass it to revokeMySession."
          },
          "browser": {
            "type": [
              "string",
              "null"
            ],
            "description": "The browser, such as Chrome, Safari, Firefox, Edge, Cốc Cốc, Zalo or Samsung Internet; null when it could not be told."
          },
          "os": {
            "type": [
              "string",
              "null"
            ],
            "description": "The operating system: Windows, macOS, iOS, Android, ChromeOS or Linux; null when it could not be told."
          },
          "mobile": {
            "type": "boolean",
            "description": "Whether the browser said it runs on a phone."
          },
          "created_at": {
            "type": "integer",
            "description": "When the session was opened (sign-in), Unix seconds rounded down to the minute."
          },
          "last_seen_at": {
            "type": "integer",
            "description": "When the session was last used, Unix seconds rounded down to the minute (recorded at most once a minute)."
          },
          "current": {
            "type": "boolean",
            "description": "Whether this is the session making the request."
          }
        },
        "example": {
          "id": 42,
          "browser": "Chrome",
          "os": "Windows",
          "mobile": false,
          "created_at": 1790060400,
          "last_seen_at": 1790086380,
          "current": true
        }
      },
      "SignedInSessionList": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SignedInSession"
            },
            "description": "The live sessions, the current one first, then the most recently used."
          }
        },
        "example": {
          "items": [
            {
              "id": 42,
              "browser": "Chrome",
              "os": "Windows",
              "mobile": false,
              "created_at": 1790060400,
              "last_seen_at": 1790086380,
              "current": true
            },
            {
              "id": 37,
              "browser": "Safari",
              "os": "iOS",
              "mobile": true,
              "created_at": 1789899960,
              "last_seen_at": 1789999980,
              "current": false
            }
          ]
        }
      },
      "SignedInSessionRevoked": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "revoked"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "revoked": {
            "const": true
          }
        },
        "example": {
          "id": 37,
          "revoked": true
        }
      },
      "SessionsRevoked": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "sessions_revoked"
        ],
        "properties": {
          "sessions_revoked": {
            "type": "integer",
            "minimum": 0,
            "description": "How many live sessions were ended."
          }
        },
        "example": {
          "sessions_revoked": 2
        }
      },
      "MemberSessionsRevoke": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Required from a platform admin (CropPath support): one line, kept in the company's activity log. Ignored for a company admin."
          }
        },
        "example": {
          "reason": "Phone lost at the collection point, confirmed by the company director"
        }
      },
      "MemberSessionsRevoked": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "user_id",
          "sessions_revoked"
        ],
        "properties": {
          "user_id": {
            "type": "integer"
          },
          "sessions_revoked": {
            "type": "integer",
            "minimum": 0,
            "description": "How many live sessions of the member were ended."
          }
        },
        "example": {
          "user_id": 7,
          "sessions_revoked": 2
        }
      },
      "SupportRequestUser": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "email",
          "display_name"
        ],
        "description": "The member who sent the request.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "email": {
            "type": "string"
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "id": 7,
          "email": "op@coop.example",
          "display_name": "Lan"
        }
      },
      "SupportRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "body",
          "created_at",
          "id",
          "record_id",
          "reply",
          "status",
          "subject",
          "tenant",
          "updated_at",
          "user"
        ],
        "description": "A support request as its company sees it (never who at CropPath changed it).",
        "properties": {
          "id": {
            "type": "integer"
          },
          "tenant": {
            "type": "string",
            "description": "The company the request came from."
          },
          "user": {
            "$ref": "#/components/schemas/SupportRequestUser"
          },
          "subject": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Plain text, as typed (trimmed)."
          },
          "body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 5000,
            "description": "Plain text, as typed (trimmed): never HTML or markdown; line breaks are kept."
          },
          "record_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "The record the request is about (a lot code, device id, public id, ...), or null."
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "in_progress",
              "answered",
              "closed"
            ],
            "description": "`open` (new), `in_progress` (CropPath is on it), `answered` (CropPath replied and waits for the company) or `closed`."
          },
          "reply": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 5000,
            "description": "CropPath's reply (plain text), or null."
          },
          "created_at": {
            "type": "number",
            "description": "Seconds since 1970 (UTC)."
          },
          "updated_at": {
            "type": "number",
            "description": "When the request was sent or CropPath last changed it."
          }
        },
        "example": {
          "id": 12,
          "tenant": "coop-dl",
          "user": {
            "id": 7,
            "email": "op@coop.example",
            "display_name": "Lan"
          },
          "subject": "Scale at line A1 shows no weight",
          "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
          "record_id": "LOT-2026-001",
          "status": "answered",
          "reply": "Please restart the scale; it reconnects in a minute.",
          "created_at": 1790000000.5,
          "updated_at": 1790003600.5
        }
      },
      "PlatformSupportRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "body",
          "created_at",
          "id",
          "record_id",
          "reply",
          "status",
          "subject",
          "tenant",
          "updated_at",
          "updated_by",
          "user"
        ],
        "description": "A support request in the platform's queue.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "tenant": {
            "type": "string",
            "description": "The company the request came from."
          },
          "user": {
            "$ref": "#/components/schemas/SupportRequestUser"
          },
          "subject": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Plain text, as typed (trimmed)."
          },
          "body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 5000,
            "description": "Plain text, as typed (trimmed): never HTML or markdown; line breaks are kept."
          },
          "record_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "The record the request is about (a lot code, device id, public id, ...), or null."
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "in_progress",
              "answered",
              "closed"
            ],
            "description": "`open` (new), `in_progress` (CropPath is on it), `answered` (CropPath replied and waits for the company) or `closed`."
          },
          "reply": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 5000,
            "description": "CropPath's reply (plain text), or null."
          },
          "created_at": {
            "type": "number",
            "description": "Seconds since 1970 (UTC)."
          },
          "updated_at": {
            "type": "number",
            "description": "When the request was sent or CropPath last changed it."
          },
          "updated_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "The platform admin who last changed it; null until then."
          }
        },
        "example": {
          "id": 12,
          "tenant": "coop-dl",
          "user": {
            "id": 7,
            "email": "op@coop.example",
            "display_name": "Lan"
          },
          "subject": "Scale at line A1 shows no weight",
          "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
          "record_id": "LOT-2026-001",
          "status": "answered",
          "reply": "Please restart the scale; it reconnects in a minute.",
          "created_at": 1790000000.5,
          "updated_at": 1790003600.5,
          "updated_by": "support@croppath.example"
        }
      },
      "SupportRequestPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/SupportRequest"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 12,
              "tenant": "coop-dl",
              "user": {
                "id": 7,
                "email": "op@coop.example",
                "display_name": "Lan"
              },
              "subject": "Scale at line A1 shows no weight",
              "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
              "record_id": "LOT-2026-001",
              "status": "answered",
              "reply": "Please restart the scale; it reconnects in a minute.",
              "created_at": 1790000000.5,
              "updated_at": 1790003600.5
            }
          ],
          "next_cursor": null
        }
      },
      "PlatformSupportRequestPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/PlatformSupportRequest"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 12,
              "tenant": "coop-dl",
              "user": {
                "id": 7,
                "email": "op@coop.example",
                "display_name": "Lan"
              },
              "subject": "Scale at line A1 shows no weight",
              "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
              "record_id": "LOT-2026-001",
              "status": "answered",
              "reply": "Please restart the scale; it reconnects in a minute.",
              "created_at": 1790000000.5,
              "updated_at": 1790003600.5,
              "updated_by": "support@croppath.example"
            }
          ],
          "next_cursor": null
        }
      },
      "SupportRequestCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "subject",
          "body"
        ],
        "properties": {
          "subject": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "1 to 200 characters after trimming; no line breaks or other control characters."
          },
          "body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 5000,
            "description": "1 to 5000 characters after trimming; line breaks and tabs allowed, no other control characters. Stored and shown as plain text."
          },
          "record_id": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Optional: at most 100 letters, digits and . _ : / # -, starting with a letter or digit; blank or null for none."
          }
        },
        "example": {
          "subject": "Scale at line A1 shows no weight",
          "body": "Since this morning the scale at line A1 shows 0 kg for every fruit.",
          "record_id": "LOT-2026-001"
        }
      },
      "SupportRequestUpdate": {
        "type": "object",
        "additionalProperties": false,
        "minProperties": 1,
        "description": "A status, a reply, or both.",
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "open",
              "in_progress",
              "answered",
              "closed"
            ],
            "description": "`open` (new), `in_progress` (CropPath is on it), `answered` (CropPath replied and waits for the company) or `closed`."
          },
          "reply": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 5000,
            "description": "Plain text; line breaks allowed; null or blank clears it."
          }
        },
        "example": {
          "status": "answered",
          "reply": "Please restart the scale; it reconnects in a minute."
        }
      },
      "LiveAnnouncement": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "ends_at",
          "id",
          "level",
          "starts_at",
          "text"
        ],
        "description": "An announcement showing now in the staff shell.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Plain text, one line."
          },
          "level": {
            "type": "string",
            "enum": [
              "info",
              "warning"
            ]
          },
          "starts_at": {
            "type": "number",
            "description": "Shown from this time (seconds since 1970, UTC)."
          },
          "ends_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Shown until this time; null until expired."
          }
        },
        "example": {
          "id": 3,
          "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
          "level": "warning",
          "starts_at": 1790000000.5,
          "ends_at": 1790086400.5
        }
      },
      "Announcement": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "created_at",
          "created_by",
          "ends_at",
          "expired_at",
          "expired_by",
          "id",
          "level",
          "starts_at",
          "state",
          "text"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Plain text, one line."
          },
          "level": {
            "type": "string",
            "enum": [
              "info",
              "warning"
            ]
          },
          "starts_at": {
            "type": "number",
            "description": "Shown from this time (seconds since 1970, UTC)."
          },
          "ends_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Shown until this time; null until expired."
          },
          "state": {
            "type": "string",
            "enum": [
              "live",
              "scheduled",
              "ended"
            ],
            "description": "`scheduled` before `starts_at`; `ended` once expired or past `ends_at`."
          },
          "created_at": {
            "type": "number"
          },
          "created_by": {
            "type": "string"
          },
          "expired_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "expired_by": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "id": 3,
          "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
          "level": "warning",
          "starts_at": 1790000000.5,
          "ends_at": 1790086400.5,
          "state": "live",
          "created_at": 1790000000.5,
          "created_by": "support@croppath.example",
          "expired_at": null,
          "expired_by": null
        }
      },
      "AnnouncementPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/Announcement"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 3,
              "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
              "level": "warning",
              "starts_at": 1790000000.5,
              "ends_at": 1790086400.5,
              "state": "live",
              "created_at": 1790000000.5,
              "created_by": "support@croppath.example",
              "expired_at": null,
              "expired_by": null
            }
          ],
          "next_cursor": null
        }
      },
      "AnnouncementCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "text"
        ],
        "properties": {
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "1 to 500 characters after trimming, one line, plain text."
          },
          "level": {
            "type": "string",
            "enum": [
              "info",
              "warning"
            ],
            "default": "info"
          },
          "starts_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When it starts showing (default now; a past time means now); at most a year ahead."
          },
          "ends_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When it stops showing: later than the start and at most a year after it; null shows it until expired."
          }
        },
        "example": {
          "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
          "level": "warning",
          "ends_at": 1790086400.5
        }
      },
      "Help": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "status_page_url",
          "announcements"
        ],
        "properties": {
          "status_page_url": {
            "type": [
              "string",
              "null"
            ],
            "format": "uri",
            "description": "CropPath's status page (an https address), or null: hide the link."
          },
          "announcements": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/LiveAnnouncement"
            },
            "description": "The announcements showing now, newest first."
          }
        },
        "example": {
          "status_page_url": "https://status.croppath.example",
          "announcements": [
            {
              "id": 3,
              "text": "Planned maintenance on Sunday 22:00 to 23:00 (Vietnam time): the console may be slow.",
              "level": "warning",
              "starts_at": 1790000000.5,
              "ends_at": 1790086400.5
            }
          ]
        }
      },
      "FacilityProposalCreate": {
        "type": "object",
        "required": [
          "code",
          "name"
        ],
        "additionalProperties": false,
        "description": "SELF-2-8 (#197): what a company admin gives when proposing a facility. Never the slug or the GACC PHC code: CropPath sets both when it approves the proposal.",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[A-Z]{2}-[A-Z0-9]{2,8}-[0-9A-Z]{2,12}$"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "address": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 300
          },
          "province": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: the province as free text. Send `province_code` and `commune_code` instead. A body that gives the address as text only is still accepted until the sunset: the record is stored as not yet coded (`address_status` `needs_commune`) and the answer carries the `Deprecation`, `Sunset` and `Link` headers.",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "district": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 100,
            "description": "Deprecated (#273), sunset 1 May 2027: Viet Nam has had no district level since 1 July 2025. Send `province_code` and `commune_code` instead; with them `district` must be absent or null (400 `district_with_codes`).",
            "deprecated": true,
            "x-sdk-object": {
              "type": [
                "string",
                "null"
              ],
              "maxLength": 100
            }
          },
          "province_code": {
            "description": "#273: the province (tỉnh or thành phố trực thuộc trung ương) by its official 2-digit code in the administrative units list in force (`getAdminUnits`). Sent with `commune_code`, both or neither; with them `province`, `district` and `commune` must be absent or null and the server writes the official names.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{2}$",
            "x-not-in-sdk": true
          },
          "commune_code": {
            "description": "#273: the commune (xã, phường or đặc khu) by its official 5-digit code in the administrative units list in force (`getAdminUnits` with `province`). Sent with `province_code`, both or neither; the commune must lie in that province by the list, never by its digits.",
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{5}$",
            "x-not-in-sdk": true
          },
          "lines": {
            "type": "array",
            "maxItems": 32,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "minLength": 1,
              "maxLength": 32
            }
          }
        },
        "example": {
          "code": "VN-TGPH-044",
          "name": "Hoa Hung packing house",
          "address": "Cai Be, Tien Giang",
          "province": "Tien Giang",
          "district": "Cai Be",
          "lines": [
            "A1"
          ]
        }
      },
      "FacilityProposal": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "tenant",
          "tenant_name",
          "name",
          "address",
          "province",
          "district",
          "lines",
          "slug",
          "proposed_at",
          "proposed_by"
        ],
        "description": "SELF-2-8 (#197): a company's facility proposal waiting for CropPath, in the platform's queue.",
        "properties": {
          "code": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "tenant_name": {
            "type": "string",
            "description": "The proposing company's name."
          },
          "name": {
            "type": "string"
          },
          "address": {
            "type": [
              "string",
              "null"
            ]
          },
          "province": {
            "type": [
              "string",
              "null"
            ]
          },
          "district": {
            "type": [
              "string",
              "null"
            ]
          },
          "lines": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "slug": {
            "type": "string",
            "description": "The default slug of the code; the approval may set another."
          },
          "proposed_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "proposed_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who proposed it (the account's email)."
          }
        },
        "example": {
          "code": "VN-TGPH-044",
          "tenant": "coop-dl",
          "tenant_name": "Coop DL",
          "name": "Hoa Hung packing house",
          "address": "Cai Be, Tien Giang",
          "province": "Tien Giang",
          "district": "Cai Be",
          "lines": [
            "A1"
          ],
          "slug": "vn-tgph-044",
          "proposed_at": 1790000000.5,
          "proposed_by": "admin@coop.example"
        }
      },
      "FacilityProposalPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/FacilityProposal"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "items": [
            {
              "code": "VN-TGPH-044",
              "tenant": "coop-dl",
              "tenant_name": "Coop DL",
              "name": "Hoa Hung packing house",
              "address": "Cai Be, Tien Giang",
              "province": "Tien Giang",
              "district": "Cai Be",
              "lines": [
                "A1"
              ],
              "slug": "vn-tgph-044",
              "proposed_at": 1790000000.5,
              "proposed_by": "admin@coop.example"
            }
          ],
          "next_cursor": null
        }
      },
      "FacilityProposalApproval": {
        "type": "object",
        "additionalProperties": false,
        "description": "SELF-2-8 (#197): what CropPath sets when it approves a proposal (both optional; the slug is the facility's did:web path).",
        "properties": {
          "slug": {
            "type": "string",
            "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
            "maxLength": 64
          },
          "gacc_phc_code": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 64
          }
        },
        "example": {
          "slug": "hoahung",
          "gacc_phc_code": "VNPH-TG-044"
        }
      },
      "FacilityProposalRejection": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Shown to the company in its activity log."
          }
        },
        "example": {
          "reason": "This code belongs to another company's packing house."
        }
      },
      "FacilityProposalRejected": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "tenant",
          "name",
          "reason"
        ],
        "description": "SELF-2-8 (#197): the proposal CropPath rejected (it is deleted, so its code is free again).",
        "properties": {
          "code": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "reason": {
            "type": "string"
          }
        },
        "example": {
          "code": "VN-TGPH-044",
          "tenant": "coop-dl",
          "name": "Hoa Hung packing house",
          "reason": "This code belongs to another company's packing house."
        }
      },
      "CompanyExport": {
        "type": "object",
        "description": "SELF-2-3 (#192). One request for the selected company's full data archive and its state. The archive layout (files, columns, encoding, times) is documented at /developers/downloads/company-export.md.",
        "required": [
          "id",
          "status",
          "requested_by",
          "requested_at",
          "started_at",
          "finished_at",
          "expires_at",
          "size",
          "sha256",
          "file_name",
          "error"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "status": {
            "type": "string",
            "enum": [
              "queued",
              "running",
              "ready",
              "failed",
              "expired"
            ],
            "description": "`queued` until the background job takes it, `running` while it builds the archive, `ready` to download until `expires_at`, `failed` when the build failed (request a new one), `expired` once its 24 hours are over and the file is deleted."
          },
          "requested_by": {
            "type": "string",
            "description": "Who asked for it (the signed-in user's email)."
          },
          "requested_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "started_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds when the job started building it."
          },
          "finished_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds when the build ended (ready or failed)."
          },
          "expires_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "While ready: Unix seconds after which the download is refused (24 hours after the archive was ready); null otherwise."
          },
          "size": {
            "type": [
              "integer",
              "null"
            ],
            "description": "While ready: the archive's size in bytes."
          },
          "sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "While ready: the SHA-256 of the archive, to check the downloaded file."
          },
          "file_name": {
            "type": [
              "string",
              "null"
            ],
            "description": "While ready: the file name the download is saved under (croppath-export-<company>-<request time, UTC>.zip)."
          },
          "error": {
            "type": [
              "string",
              "null"
            ],
            "description": "Why the build failed: `build_failed` or `interrupted` (the server stopped while building it); null otherwise."
          }
        },
        "example": {
          "id": 12,
          "status": "ready",
          "requested_by": "admin@coop.example",
          "requested_at": 1790000000.5,
          "started_at": 1790000030.0,
          "finished_at": 1790000041.25,
          "expires_at": 1790086441.25,
          "size": 1843211,
          "sha256": "9f2c4a7d1e0b6c3f8a5d2e7b4c1f9a6d3e0b7c4f1a8d5e2b9c6f3a0d7e4b1c8f",
          "file_name": "croppath-export-coop-dl-20260921T143320Z.zip",
          "error": null
        }
      },
      "CompanyExportList": {
        "type": "object",
        "description": "SELF-2-3 (#192). The selected company's 20 newest export requests, newest first, and the limits.",
        "required": [
          "items",
          "max_per_day",
          "download_hours"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CompanyExport"
            }
          },
          "max_per_day": {
            "type": "integer",
            "description": "How many exports the company may request in any 24 hours."
          },
          "download_hours": {
            "type": "integer",
            "description": "How long a ready archive can be downloaded."
          }
        },
        "example": {
          "items": [
            {
              "id": 13,
              "status": "queued",
              "requested_by": "admin@coop.example",
              "requested_at": 1790090000.0,
              "started_at": null,
              "finished_at": null,
              "expires_at": null,
              "size": null,
              "sha256": null,
              "file_name": null,
              "error": null
            },
            {
              "id": 12,
              "status": "ready",
              "requested_by": "admin@coop.example",
              "requested_at": 1790000000.5,
              "started_at": 1790000030.0,
              "finished_at": 1790000041.25,
              "expires_at": 1790086441.25,
              "size": 1843211,
              "sha256": "9f2c4a7d1e0b6c3f8a5d2e7b4c1f9a6d3e0b7c4f1a8d5e2b9c6f3a0d7e4b1c8f",
              "file_name": "croppath-export-coop-dl-20260921T143320Z.zip",
              "error": null
            }
          ],
          "max_per_day": 3,
          "download_hours": 24
        }
      },
      "NotificationKind": {
        "type": "string",
        "enum": [
          "invitation_accepted",
          "invitation_expiring",
          "webhook_disabled",
          "api_token_expiring",
          "facility_approved",
          "facility_refused",
          "growing_area_approved",
          "report_filed",
          "signing_key_missing",
          "alarm_raised"
        ],
        "x-sdk-enum": [
          "invitation_accepted",
          "invitation_expiring",
          "webhook_disabled",
          "api_token_expiring",
          "facility_approved",
          "facility_refused",
          "growing_area_approved",
          "report_filed",
          "signing_key_missing"
        ],
        "description": "What happened. `invitation_accepted` {email, role}; `invitation_expiring` {email, role, expires_at}; `webhook_disabled` {subscription_id, description, failures}; `api_token_expiring` {token_id, name, expires_at}; `facility_approved` {code, name}; `facility_refused` {code, name, reason}; `growing_area_approved` {code, name}; `report_filed` {report_id, lot, category}; `signing_key_missing` {facility, name, open_lots}; `alarm_raised` {alarm_id, alarm_kind, priority, device, zone, area} (#361: an urgent or warning alarm of the irrigation cockpit was raised, to the company's admins, the operators of its facility getting the email only; GET /v1/alarms/{id}). Clients show an unknown kind generically: new kinds may be added.",
        "x-sdk-description": "What happened. `invitation_accepted` {email, role}; `invitation_expiring` {email, role, expires_at}; `webhook_disabled` {subscription_id, description, failures}; `api_token_expiring` {token_id, name, expires_at}; `facility_approved` {code, name}; `facility_refused` {code, name, reason}; `growing_area_approved` {code, name}; `report_filed` {report_id, lot, category}; `signing_key_missing` {facility, name, open_lots}. Clients show an unknown kind generically: new kinds may be added.",
        "example": "api_token_expiring"
      },
      "NotificationParams": {
        "type": "object",
        "additionalProperties": false,
        "description": "The kind's parameters (see NotificationKind): identifiers, names and times only, never rendered text.",
        "properties": {
          "email": {
            "type": "string",
            "description": "The invited person's sign-in email."
          },
          "role": {
            "type": "string",
            "enum": [
              "tenant_admin",
              "operator",
              "auditor",
              "agronomist"
            ],
            "description": "The invited role.",
            "x-sdk-enum": [
              "tenant_admin",
              "operator",
              "auditor"
            ]
          },
          "expires_at": {
            "type": "number",
            "description": "When the invitation or token expires (Unix seconds)."
          },
          "subscription_id": {
            "type": "integer",
            "description": "The webhook subscription turned off."
          },
          "description": {
            "type": "string",
            "description": "The webhook's own description (may be empty)."
          },
          "failures": {
            "type": "integer",
            "description": "Failed delivery attempts in a row."
          },
          "token_id": {
            "type": "integer"
          },
          "name": {
            "type": [
              "string",
              "null"
            ],
            "description": "The token's, facility's or growing area's name."
          },
          "code": {
            "type": "string",
            "description": "The facility or growing area code."
          },
          "reason": {
            "type": "string",
            "description": "Why CropPath refused the facility proposal."
          },
          "report_id": {
            "type": "integer"
          },
          "lot": {
            "type": "string",
            "description": "The lot code a public report names."
          },
          "category": {
            "type": "string",
            "enum": [
              "label_peeled",
              "scanned_many",
              "ripeness_off",
              "other"
            ]
          },
          "facility": {
            "type": "string",
            "description": "The facility code missing a signing key."
          },
          "open_lots": {
            "type": "integer",
            "description": "Its lots not closed yet (draft, open or paused)."
          },
          "alarm_id": {
            "type": "integer",
            "description": "#361: the alarm raised (GET /v1/alarms/{id}).",
            "x-not-in-sdk": true
          },
          "alarm_kind": {
            "type": "string",
            "description": "#361: the alarm's catalog kind.",
            "x-not-in-sdk": true
          },
          "priority": {
            "type": "string",
            "enum": [
              "urgent",
              "warning",
              "notice"
            ],
            "description": "#361: the alarm's priority.",
            "x-not-in-sdk": true
          },
          "device": {
            "type": [
              "string",
              "null"
            ],
            "description": "#361: the alarm's device.",
            "x-not-in-sdk": true
          },
          "zone": {
            "type": [
              "integer",
              "null"
            ],
            "description": "#361: the alarm's controller zone.",
            "x-not-in-sdk": true
          },
          "area": {
            "type": [
              "string",
              "null"
            ],
            "description": "#361: the alarm's growing area code.",
            "x-not-in-sdk": true
          }
        },
        "example": {
          "token_id": 7,
          "name": "erp-sync",
          "expires_at": 1797776000.5
        }
      },
      "Notification": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "kind",
          "params",
          "created_at",
          "read_at"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "kind": {
            "$ref": "#/components/schemas/NotificationKind"
          },
          "params": {
            "$ref": "#/components/schemas/NotificationParams"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "read_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When the caller read it; null while unread."
          }
        },
        "example": {
          "id": 41,
          "kind": "api_token_expiring",
          "params": {
            "token_id": 7,
            "name": "erp-sync",
            "expires_at": 1797776000.5
          },
          "created_at": 1797000000.5,
          "read_at": null
        }
      },
      "NotificationPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "unread",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/Notification"
            }
          },
          "unread": {
            "type": "integer",
            "minimum": 0,
            "description": "The caller's unread notifications in this company."
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 41,
              "kind": "api_token_expiring",
              "params": {
                "token_id": 7,
                "name": "erp-sync",
                "expires_at": 1797776000.5
              },
              "created_at": 1797000000.5,
              "read_at": null
            }
          ],
          "unread": 1,
          "next_cursor": null
        }
      },
      "NotificationUnreadCount": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "unread"
        ],
        "properties": {
          "unread": {
            "type": "integer",
            "minimum": 0
          }
        },
        "example": {
          "unread": 3
        }
      },
      "NotificationsMarkedRead": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "marked",
          "unread"
        ],
        "properties": {
          "marked": {
            "type": "integer",
            "minimum": 0
          },
          "unread": {
            "type": "integer",
            "minimum": 0
          }
        },
        "example": {
          "marked": 3,
          "unread": 0
        }
      },
      "PersonalData": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "account_created_at",
          "account_status",
          "company",
          "display_name",
          "email",
          "facilities",
          "joined_at",
          "lab_id",
          "membership_status",
          "notice_accepted_at",
          "recent_sign_ins",
          "roles",
          "two_factor",
          "user_id"
        ],
        "description": "SELF-2-9 (#198). What the platform holds about the signed-in member in the selected company. Never a secret: no password hash, session token, address hash, user agent or two-step secret.",
        "properties": {
          "user_id": {
            "type": "integer"
          },
          "email": {
            "type": "string"
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "company": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "id",
              "name"
            ],
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "roles": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "tenant_admin",
                "operator",
                "auditor",
                "agronomist",
                "lab",
                "platform_admin"
              ],
              "x-sdk-enum": [
                "tenant_admin",
                "operator",
                "auditor",
                "lab",
                "platform_admin"
              ]
            },
            "description": "The member's roles in this company, the company-managed ones first."
          },
          "facilities": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "string"
            },
            "description": "An operator's facility codes; null for every facility or for another role."
          },
          "lab_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The lab of a lab membership, or null."
          },
          "membership_status": {
            "type": "string",
            "enum": [
              "active",
              "disabled"
            ]
          },
          "account_status": {
            "type": "string",
            "enum": [
              "active",
              "disabled"
            ]
          },
          "account_created_at": {
            "type": "number",
            "description": "Seconds since 1970 (UTC)."
          },
          "joined_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When the member joined this company, or null when not recorded."
          },
          "notice_accepted_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When the member accepted the staff privacy notice (at the invitation), or null."
          },
          "two_factor": {
            "type": "boolean",
            "description": "Whether two-step sign-in is on (never its secret)."
          },
          "recent_sign_ins": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "number"
            },
            "description": "The times of the account's most recent sign-ins that the database still keeps, newest first (sign-ins are per account, not per company)."
          },
          "agronomist": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/Agronomist"
              },
              {
                "type": "null"
              }
            ],
            "x-not-in-sdk": true,
            "description": "#351: with `agronomist=1` only: the caller's row of the platform's agronomist registry, or null without one."
          }
        },
        "example": {
          "user_id": 7,
          "email": "op@coop.example",
          "display_name": "Lan",
          "company": {
            "id": "coop-dl",
            "name": "Coop DL"
          },
          "roles": [
            "operator"
          ],
          "facilities": [
            "VN-TGPH-021"
          ],
          "lab_id": null,
          "membership_status": "active",
          "account_status": "active",
          "account_created_at": 1789000000.5,
          "joined_at": 1789000000.5,
          "notice_accepted_at": 1789000000.5,
          "two_factor": true,
          "recent_sign_ins": [
            1790000000.5,
            1789900000.5
          ]
        }
      },
      "PersonalDataRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "created_at",
          "handled_at",
          "id",
          "kind",
          "status",
          "text"
        ],
        "description": "SELF-2-9 (#198). A member's request about their personal data, as the member sees it (never who handled it).",
        "properties": {
          "id": {
            "type": "integer"
          },
          "kind": {
            "type": "string",
            "enum": [
              "access",
              "correction"
            ],
            "description": "`access`: see more of the personal data held; `correction`: correct it."
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "Plain text, as typed (trimmed): never HTML or markdown; line breaks are kept."
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "handled"
            ],
            "description": "`open` (new) or `handled` (a company admin dealt with it; final)."
          },
          "created_at": {
            "type": "number",
            "description": "Seconds since 1970 (UTC)."
          },
          "handled_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When a company admin marked it handled, or null."
          }
        },
        "example": {
          "id": 4,
          "kind": "correction",
          "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
          "status": "open",
          "created_at": 1790000000.5,
          "handled_at": null
        }
      },
      "CompanyPersonalDataRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "created_at",
          "handled_at",
          "handled_by",
          "id",
          "kind",
          "status",
          "text",
          "user"
        ],
        "description": "SELF-2-9 (#198). A member's request about their personal data, as the company's admins see it.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "kind": {
            "type": "string",
            "enum": [
              "access",
              "correction"
            ],
            "description": "`access`: see more of the personal data held; `correction`: correct it."
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "Plain text, as typed (trimmed): never HTML or markdown; line breaks are kept."
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "handled"
            ],
            "description": "`open` (new) or `handled` (a company admin dealt with it; final)."
          },
          "created_at": {
            "type": "number",
            "description": "Seconds since 1970 (UTC)."
          },
          "handled_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When a company admin marked it handled, or null."
          },
          "user": {
            "$ref": "#/components/schemas/SupportRequestUser"
          },
          "handled_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who marked it handled (an email), or null."
          }
        },
        "example": {
          "id": 4,
          "kind": "correction",
          "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
          "status": "handled",
          "created_at": 1790000000.5,
          "handled_at": 1790003600.5,
          "user": {
            "id": 7,
            "email": "op@coop.example",
            "display_name": "Lan"
          },
          "handled_by": "admin@coop.example"
        }
      },
      "PersonalDataRequestCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "kind",
          "text"
        ],
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "access",
              "correction"
            ]
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "1 to 2000 characters after trimming; line breaks and tabs allowed, no other control characters. Stored and shown as plain text."
          }
        },
        "example": {
          "kind": "correction",
          "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A."
        }
      },
      "PersonalDataRequestPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/PersonalDataRequest"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 4,
              "kind": "correction",
              "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
              "status": "open",
              "created_at": 1790000000.5,
              "handled_at": null
            }
          ],
          "next_cursor": null
        }
      },
      "CompanyPersonalDataRequestPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/CompanyPersonalDataRequest"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 4,
              "kind": "correction",
              "text": "My name is spelled Nguyễn Văn An, not Nguyen Van A.",
              "status": "handled",
              "created_at": 1790000000.5,
              "handled_at": 1790003600.5,
              "user": {
                "id": 7,
                "email": "op@coop.example",
                "display_name": "Lan"
              },
              "handled_by": "admin@coop.example"
            }
          ],
          "next_cursor": null
        }
      },
      "CompanyOffboarding": {
        "type": "object",
        "description": "SELF-2-4 (#193): whether a company is leaving CropPath. `active`: no departure. `leaving`: the read-only window (30 days from `started_at` to `window_ends_at`) in which its people still sign in, read and download the full data export, but nothing of the company may change. `left`: sign-in stopped at `left_at`; the job then revokes the company's credentials and removes its people's names and emails (`steps_done` of 3). Sealed lot records, evidence and public lot pages stay until `retention_ends_at`: the latest seal (or the end of the window when later) plus `retention_years`, which CropPath sets for each company (no default).",
        "required": [
          "status",
          "retention_years",
          "started_at",
          "window_ends_at",
          "left_at",
          "retention_ends_at",
          "steps_done"
        ],
        "additionalProperties": false,
        "properties": {
          "status": {
            "enum": [
              "active",
              "leaving",
              "left"
            ]
          },
          "retention_years": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 30,
            "description": "Years the sealed lot records are kept, counted from each lot's seal."
          },
          "started_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null while the company is active."
          },
          "window_ends_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null while the company is active."
          },
          "left_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; when sign-in stopped (status left)."
          },
          "retention_ends_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds; null while the company is active."
          },
          "steps_done": {
            "type": "integer",
            "minimum": 0,
            "maximum": 3,
            "description": "The job's steps done: 1 members off, 2 credentials revoked, 3 personal data removed."
          }
        },
        "example": {
          "status": "leaving",
          "retention_years": 5,
          "started_at": 1790000000.5,
          "window_ends_at": 1792592000.5,
          "left_at": null,
          "retention_ends_at": 1949858000.5,
          "steps_done": 0
        }
      },
      "CompanyOffboardingStart": {
        "type": "object",
        "required": [
          "retention_years"
        ],
        "additionalProperties": false,
        "properties": {
          "retention_years": {
            "type": "integer",
            "minimum": 1,
            "maximum": 30,
            "description": "How many years the company's sealed lot records, evidence and public lot pages are kept, counted from each lot's seal (owner decision D-S4: no default; CropPath sets it for each company)."
          }
        },
        "example": {
          "retention_years": 5
        }
      },
      "SandboxAccountCreate": {
        "type": "object",
        "additionalProperties": false,
        "maxProperties": 0,
        "description": "The body of a sandbox account request (#218): empty, or an empty object. The sandbox chooses everything."
      },
      "SandboxAccount": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "tenant_id",
          "api_token",
          "expires_at",
          "base_url"
        ],
        "description": "A new sandbox company and its API token (#218). The token is shown this once: only its SHA-256 is stored.",
        "properties": {
          "tenant_id": {
            "type": "string",
            "pattern": "^sbx-[a-z2-7]{16}$",
            "description": "The new company's id, the tenant every record of the token belongs to."
          },
          "api_token": {
            "type": "string",
            "pattern": "^agt_[A-Za-z0-9_-]{43}$",
            "description": "An API token of the company, role tenant_admin, sent as `Authorization: Bearer`. Shown once."
          },
          "expires_at": {
            "type": "number",
            "description": "When the token stops working: 24 hours after the creation, Unix seconds."
          },
          "base_url": {
            "type": "string",
            "format": "uri",
            "description": "The sandbox API's address: the requests go to `<base_url>/v1/...`."
          }
        },
        "example": {
          "tenant_id": "sbx-k3m7q2xw5zr4tn6p",
          "api_token": "agt_Q2hhbmdlIG1lIG5vdzogdGhpcyBpcyBhbiBleGFtcGx",
          "expires_at": 1790086400.5,
          "base_url": "https://sandbox-txng.theio.vn"
        }
      },
      "DevicePlacementCreate": {
        "type": "object",
        "description": "SENS-A2 (#225): a new placement version of a device, recorded by a platform admin acting for the device's company (X-Tenant). `mobility` and `key_protection` are required. A `fixed` placement must also give the growing area it is bound to (one of the company's), the surveyed install point (`lat`, `lon`, `accuracy_m`) and the commissioning record: `photo_sha256` (a JPEG or PNG the company's records hold, uploaded first with PUT /v1/attachments/{sha256} for the same company), `fix_at`, `installed_at` and `installer`. A `mobile` placement may leave them out. Times are Unix seconds, from 2020-01-01 and at most 300 s ahead of the server clock; `fix_at` is at most 7 days before `installed_at` and never after it (300 s of clock drift allowed).",
        "additionalProperties": false,
        "required": [
          "mobility",
          "key_protection"
        ],
        "properties": {
          "mobility": {
            "type": "string",
            "enum": [
              "fixed",
              "mobile"
            ],
            "description": "`fixed`: a station or probe installed in one place. `mobile`: a handheld device or phone."
          },
          "key_protection": {
            "type": "string",
            "enum": [
              "hardware",
              "software"
            ],
            "description": "The platform admin's statement of where the device keeps its signing key: `hardware` (a secure element, TPM or attested phone key store) or `software`. Recorded as stated; not verified by the platform. Owner decision Q3 (#223): location claims count as recorded by a device only with `hardware`, and never for a device registered before placements existed."
          },
          "gnss": {
            "type": "boolean",
            "description": "The device has its own GNSS receiver. Default false."
          },
          "growing_area": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256,
            "description": "Code of a growing area of the device's company; required for `fixed`."
          },
          "lat": {
            "type": "number",
            "minimum": -90,
            "maximum": 90,
            "description": "Install point latitude, WGS84."
          },
          "lon": {
            "type": "number",
            "minimum": -180,
            "maximum": 180,
            "description": "Install point longitude, WGS84."
          },
          "accuracy_m": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 10000,
            "description": "Accuracy of the install point fix in metres. `lat`, `lon` and `accuracy_m` come together."
          },
          "fix_at": {
            "type": "number",
            "minimum": 1577836800,
            "description": "When the GPS fix of the install point was taken: at most 7 days before `installed_at`, never after it."
          },
          "installed_at": {
            "type": "number",
            "minimum": 1577836800,
            "description": "When the device was installed there: the version is in force from then (from when it was recorded when absent), and may not start before the current version."
          },
          "installer": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Who installed it."
          },
          "photo_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the installer's photo of the installed device (JPEG or PNG)."
          },
          "depth_cm": {
            "type": "number",
            "minimum": 0,
            "maximum": 10000,
            "description": "Probe depth in centimetres."
          },
          "sensor_serial": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100,
            "description": "Probe serial number."
          },
          "note": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Why it was placed or moved."
          }
        },
        "example": {
          "mobility": "fixed",
          "key_protection": "hardware",
          "growing_area": "VN-TG-CL-0042",
          "lat": 10.3512345,
          "lon": 106.1234567,
          "accuracy_m": 3.5,
          "fix_at": 1790100000.0,
          "installed_at": 1790100600.0,
          "installer": "Nguyen Van A",
          "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
          "depth_cm": 30.0,
          "sensor_serial": "RS485-4IN1-00172",
          "note": "Moved to block B after replanting"
        }
      },
      "DevicePlacementRemoval": {
        "type": "object",
        "description": "SENS-A2 (#225): the device was taken out. A new placement version that ends the binding of the installation in force (it keeps that version's `mobility`, `key_protection` and `gnss`; growing area, install point and commissioning record are null). Only a device whose current version is an installation can be removed; a later installation is a new version again. While a removal is in force, an envelope of the device that claims a growing area raises a `device_removed` alert; when the installation the removal ended was `fixed`, the envelope is also held: as `growing_area_mismatch` when it claims another growing area than that installation's, else as `device_removed`.",
        "additionalProperties": false,
        "required": [
          "removed_at"
        ],
        "properties": {
          "removed_at": {
            "type": "number",
            "minimum": 1577836800,
            "description": "When the device was taken out, Unix seconds: from 2020-01-01, at most 300 s ahead of the server clock, and not before the current version starts."
          },
          "note": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Why it was taken out."
          }
        },
        "example": {
          "removed_at": 1790200000.0,
          "note": "Taken out for repair"
        }
      },
      "DevicePlacement": {
        "type": "object",
        "description": "SENS-A2 (#225): one placement version of a device, never changed once recorded: an installation, or a removal (`removed_at` set, no binding). A version is in force from `installed_at` (for a removal `removed_at`, else `recorded_at`) until `valid_until`, when the next version starts (null for the current one). Ingest holds an envelope as `growing_area_mismatch` when the version in force at its time is `fixed` and bound to another growing area than the one the envelope claims; an envelope timed before the first version is checked against the first version. While a removal is in force, an envelope claiming a growing area raises a `device_removed` alert and, when the ended installation was `fixed`, is held (`growing_area_mismatch` for another area than that installation's, else `device_removed`).",
        "additionalProperties": false,
        "required": [
          "device_id",
          "version",
          "mobility",
          "key_protection",
          "gnss",
          "growing_area",
          "lat",
          "lon",
          "accuracy_m",
          "fix_at",
          "installed_at",
          "installer",
          "photo_sha256",
          "depth_cm",
          "sensor_serial",
          "note",
          "removed_at",
          "recorded_at",
          "valid_until"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "version": {
            "type": "integer",
            "minimum": 1,
            "description": "1 for the first placement, then 2, 3, ..."
          },
          "mobility": {
            "type": "string",
            "enum": [
              "fixed",
              "mobile"
            ]
          },
          "key_protection": {
            "type": "string",
            "enum": [
              "hardware",
              "software"
            ]
          },
          "gnss": {
            "type": "boolean"
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ]
          },
          "lat": {
            "type": [
              "number",
              "null"
            ]
          },
          "lon": {
            "type": [
              "number",
              "null"
            ]
          },
          "accuracy_m": {
            "type": [
              "number",
              "null"
            ]
          },
          "fix_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "installed_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "installer": {
            "type": [
              "string",
              "null"
            ]
          },
          "photo_sha256": {
            "type": [
              "string",
              "null"
            ]
          },
          "depth_cm": {
            "type": [
              "number",
              "null"
            ]
          },
          "sensor_serial": {
            "type": [
              "string",
              "null"
            ]
          },
          "note": {
            "type": [
              "string",
              "null"
            ]
          },
          "removed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Set on a removal version: when the device was taken out."
          },
          "recorded_by": {
            "type": "string",
            "description": "The CropPath platform admin who recorded it; present for platform admins only."
          },
          "recorded_at": {
            "type": "number"
          },
          "valid_until": {
            "type": [
              "number",
              "null"
            ],
            "description": "When the next version starts; null for the current version."
          }
        },
        "example": {
          "device_id": "soil-07",
          "version": 2,
          "mobility": "fixed",
          "key_protection": "hardware",
          "gnss": false,
          "growing_area": "VN-TG-CL-0042",
          "lat": 10.3512345,
          "lon": 106.1234567,
          "accuracy_m": 3.5,
          "fix_at": 1790100000.0,
          "installed_at": 1790100600.0,
          "installer": "Nguyen Van A",
          "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
          "depth_cm": 30.0,
          "sensor_serial": "RS485-4IN1-00172",
          "note": "Moved to block B after replanting",
          "removed_at": null,
          "recorded_at": 1790101000.0,
          "valid_until": null
        }
      },
      "DevicePlacements": {
        "type": "object",
        "description": "SENS-A2 (#225): a device's placement versions, newest first (at most 1000).",
        "additionalProperties": false,
        "required": [
          "device_id",
          "registered_before_placements",
          "items"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "registered_before_placements": {
            "type": "boolean",
            "description": "The device existed before placements were introduced (owner decision Q3, #223): its location claims stay Self-declared until it is replaced, whatever its placement says."
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DevicePlacement"
            }
          }
        },
        "example": {
          "device_id": "soil-07",
          "registered_before_placements": false,
          "items": [
            {
              "device_id": "soil-07",
              "version": 2,
              "mobility": "fixed",
              "key_protection": "hardware",
              "gnss": false,
              "growing_area": "VN-TG-CL-0042",
              "lat": 10.3512345,
              "lon": 106.1234567,
              "accuracy_m": 3.5,
              "fix_at": 1790100000.0,
              "installed_at": 1790100600.0,
              "installer": "Nguyen Van A",
              "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
              "depth_cm": 30.0,
              "sensor_serial": "RS485-4IN1-00172",
              "note": "Moved to block B after replanting",
              "removed_at": null,
              "recorded_at": 1790101000.0,
              "valid_until": null
            },
            {
              "device_id": "soil-07",
              "version": 1,
              "mobility": "fixed",
              "key_protection": "hardware",
              "gnss": false,
              "growing_area": "VN-TG-CL-0042",
              "lat": 10.3509876,
              "lon": 106.1229876,
              "accuracy_m": 4.0,
              "fix_at": 1780000000.0,
              "installed_at": 1780000600.0,
              "installer": "Nguyen Van A",
              "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
              "depth_cm": 30.0,
              "sensor_serial": "RS485-4IN1-00172",
              "note": null,
              "removed_at": null,
              "recorded_at": 1790101000.0,
              "valid_until": 1790100600.0
            }
          ]
        }
      },
      "PolygonVersion": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "growing_area",
          "version",
          "polygon_sha256",
          "valid_from",
          "origin"
        ],
        "description": "SENS-A1 (#224): one boundary of a growing area that the platform approved. A version never changes and is addressed by (growing_area, version); it is in force from `valid_from` until the next version's `valid_from`. The boundary and who proposed and approved it are present only for the owning tenant_admin and platform_admin; other readers get the SHA-256 and times only.",
        "properties": {
          "growing_area": {
            "type": "string"
          },
          "version": {
            "type": "integer",
            "minimum": 1,
            "description": "1, 2, ... per growing area."
          },
          "polygon_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 (hex) of the boundary's canonical GeoJSON text (compact, sorted keys, UTF-8); null when this version removed the boundary."
          },
          "valid_from": {
            "type": "number",
            "description": "Unix seconds from which this version is in force."
          },
          "origin": {
            "type": "string",
            "enum": [
              "migration",
              "area_approval",
              "proposal",
              "platform_edit"
            ],
            "description": "How the version came about: recorded when the boundary was locked (migration 69), approved with the area, a company's proposal the platform approved, or a platform admin's own edit."
          },
          "polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ],
            "description": "Present only for the owning tenant_admin and platform_admin; null: no boundary."
          },
          "proposed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Present only for the owning tenant_admin and platform_admin."
          },
          "proposed_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Present only for the owning tenant_admin and platform_admin."
          },
          "approved_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Present only for the owning tenant_admin and platform_admin."
          }
        },
        "example": {
          "growing_area": "VN-TGOR-0387",
          "version": 2,
          "polygon_sha256": "3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a",
          "valid_from": 1790003600.0,
          "origin": "proposal",
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.2,
                  10.4
                ],
                [
                  106.2,
                  10.5
                ],
                [
                  106.1,
                  10.5
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          },
          "proposed_at": 1790000000.5,
          "proposed_by": "admin@coop.example",
          "approved_by": "root@croppath.example"
        }
      },
      "PolygonProposal": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "polygon_sha256",
          "proposed_at"
        ],
        "description": "SENS-A1 (#224): a company admin's change of an approved growing area's boundary, waiting for a platform admin. The proposed boundary and who proposed it are present only for the owning tenant_admin and platform_admin.",
        "properties": {
          "polygon_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the proposed boundary; null proposes removing it."
          },
          "proposed_at": {
            "type": "number"
          },
          "polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ]
          },
          "proposed_by": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
          "proposed_at": 1790007200.5,
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.2,
                  10.4
                ],
                [
                  106.2,
                  10.5
                ],
                [
                  106.1,
                  10.5
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          },
          "proposed_by": "admin@coop.example"
        }
      },
      "PolygonHistory": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "pending",
          "items",
          "next_cursor"
        ],
        "properties": {
          "pending": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/PolygonProposal"
              },
              {
                "type": "null"
              }
            ]
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PolygonVersion"
            },
            "description": "The approved versions, newest first."
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "pending": {
            "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
            "proposed_at": 1790007200.5,
            "polygon": {
              "type": "Polygon",
              "coordinates": [
                [
                  [
                    106.1,
                    10.4
                  ],
                  [
                    106.2,
                    10.4
                  ],
                  [
                    106.2,
                    10.5
                  ],
                  [
                    106.1,
                    10.5
                  ],
                  [
                    106.1,
                    10.4
                  ]
                ]
              ]
            },
            "proposed_by": "admin@coop.example"
          },
          "items": [
            {
              "growing_area": "VN-TGOR-0387",
              "version": 2,
              "polygon_sha256": "3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a",
              "valid_from": 1790003600.0,
              "origin": "proposal",
              "polygon": {
                "type": "Polygon",
                "coordinates": [
                  [
                    [
                      106.1,
                      10.4
                    ],
                    [
                      106.2,
                      10.4
                    ],
                    [
                      106.2,
                      10.5
                    ],
                    [
                      106.1,
                      10.5
                    ],
                    [
                      106.1,
                      10.4
                    ]
                  ]
                ]
              },
              "proposed_at": 1790000000.5,
              "proposed_by": "admin@coop.example",
              "approved_by": "root@croppath.example"
            }
          ],
          "next_cursor": null
        }
      },
      "PolygonProposalQueueItem": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "tenant",
          "tenant_name",
          "name",
          "polygon",
          "polygon_sha256",
          "proposed_at",
          "proposed_by",
          "current_version",
          "current_polygon_sha256",
          "current_polygon"
        ],
        "description": "SENS-A1 (#224): a company's boundary proposal in the platform's queue, with the boundary in force.",
        "properties": {
          "code": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "tenant_name": {
            "type": "string"
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ],
            "description": "The proposed boundary; null proposes removing it."
          },
          "polygon_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "Name it when approving (POST /v1/polygon-proposals/{code}/approve)."
          },
          "proposed_at": {
            "type": "number"
          },
          "proposed_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "current_version": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The latest approved version, null when none."
          },
          "current_polygon_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the boundary in force; null when none."
          },
          "current_polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ],
            "description": "The boundary in force (the latest approved version's); null when none. Shown beside the proposed boundary so a widening is seen before it is approved."
          }
        },
        "example": {
          "code": "VN-TGOR-0387",
          "tenant": "coop-dl",
          "tenant_name": "Coop DL",
          "name": "Orchard 387",
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.2,
                  10.4
                ],
                [
                  106.2,
                  10.5
                ],
                [
                  106.1,
                  10.5
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          },
          "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
          "proposed_at": 1790007200.5,
          "proposed_by": "admin@coop.example",
          "current_version": 2,
          "current_polygon_sha256": "3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a",
          "current_polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.15,
                  10.4
                ],
                [
                  106.15,
                  10.5
                ],
                [
                  106.1,
                  10.5
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          }
        }
      },
      "PolygonProposalPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PolygonProposalQueueItem"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "items": [
            {
              "code": "VN-TGOR-0387",
              "tenant": "coop-dl",
              "tenant_name": "Coop DL",
              "name": "Orchard 387",
              "polygon": {
                "type": "Polygon",
                "coordinates": [
                  [
                    [
                      106.1,
                      10.4
                    ],
                    [
                      106.2,
                      10.4
                    ],
                    [
                      106.2,
                      10.5
                    ],
                    [
                      106.1,
                      10.5
                    ],
                    [
                      106.1,
                      10.4
                    ]
                  ]
                ]
              },
              "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
              "proposed_at": 1790007200.5,
              "proposed_by": "admin@coop.example",
              "current_version": 2,
              "current_polygon_sha256": "3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a3f5a",
              "current_polygon": {
                "type": "Polygon",
                "coordinates": [
                  [
                    [
                      106.1,
                      10.4
                    ],
                    [
                      106.15,
                      10.4
                    ],
                    [
                      106.15,
                      10.5
                    ],
                    [
                      106.1,
                      10.5
                    ],
                    [
                      106.1,
                      10.4
                    ]
                  ]
                ]
              }
            }
          ],
          "next_cursor": null
        }
      },
      "PolygonProposalApproval": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "polygon_sha256"
        ],
        "properties": {
          "polygon_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "The SHA-256 of the proposal reviewed (null for a proposed removal): a proposal replaced meanwhile is refused (409)."
          }
        },
        "example": {
          "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41"
        }
      },
      "PolygonProposalRejection": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Shown to the company in its activity log."
          }
        },
        "example": {
          "reason": "The new boundary covers the neighbour's plot."
        }
      },
      "PolygonProposalRejected": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "tenant",
          "polygon_sha256",
          "proposed_at",
          "proposed_by",
          "reason"
        ],
        "description": "SENS-A1 (#224): the boundary proposal CropPath rejected; the boundary in force stays.",
        "properties": {
          "code": {
            "type": "string"
          },
          "tenant": {
            "type": "string"
          },
          "polygon_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$"
          },
          "proposed_at": {
            "type": "number"
          },
          "proposed_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "reason": {
            "type": "string"
          }
        },
        "example": {
          "code": "VN-TGOR-0387",
          "tenant": "coop-dl",
          "polygon_sha256": "9c419c419c419c419c419c419c419c419c419c419c419c419c419c419c419c41",
          "proposed_at": 1790007200.5,
          "proposed_by": "admin@coop.example",
          "reason": "The new boundary covers the neighbour's plot."
        }
      },
      "BoundaryWalkCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "client_walk_id",
          "polygon",
          "accuracy_threshold_m",
          "started_at",
          "finished_at",
          "points"
        ],
        "description": "#248: a walk around a growing area: the simplified outline and the raw track it came from.",
        "properties": {
          "client_walk_id": {
            "type": "string",
            "format": "uuid",
            "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
            "description": "A UUID in lower case chosen by the phone for this walk: sending the same walk again with it is safe."
          },
          "polygon": {
            "$ref": "#/components/schemas/GeoJsonPolygon",
            "description": "The outline: a Polygon of exactly one closed ring, at most 1000 positions, at least 3 different corners, not crossing itself, at least 0.01 ha, each corner one of `points` with an accuracy within the threshold."
          },
          "accuracy_threshold_m": {
            "type": "number",
            "minimum": 1,
            "maximum": 50,
            "description": "Fixes less precise than this (metres) were not used for the outline."
          },
          "started_at": {
            "type": "number",
            "minimum": 1577836800,
            "description": "Unix seconds when the walk started; at most 300 s ahead of the server."
          },
          "finished_at": {
            "type": "number",
            "minimum": 1577836800,
            "description": "Unix seconds when the walk finished; not before `started_at`."
          },
          "points": {
            "type": "array",
            "minItems": 1,
            "maxItems": 20000,
            "items": {
              "type": "array",
              "minItems": 4,
              "maxItems": 4,
              "items": {
                "type": "number"
              },
              "description": "[longitude, latitude, accuracy_m, time]: WGS 84 degrees, the fix's reported accuracy in metres (above 0, at most 10000) and Unix seconds (within 60 s of the walk's start and end)."
            },
            "description": "The raw track: every fix taken during the walk, the imprecise ones included, at most 20000 (and the whole body at most 1 MiB)."
          }
        },
        "example": {
          "client_walk_id": "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b",
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.101,
                  10.4
                ],
                [
                  106.101,
                  10.401
                ],
                [
                  106.1,
                  10.401
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          },
          "accuracy_threshold_m": 15,
          "started_at": 1790000000.0,
          "finished_at": 1790000240.0,
          "points": [
            [
              106.1,
              10.4,
              4.0,
              1790000000.0
            ],
            [
              106.1005,
              10.4,
              3.5,
              1790000030.0
            ],
            [
              106.1004,
              10.4003,
              32.0,
              1790000040.0
            ],
            [
              106.101,
              10.4,
              4.2,
              1790000060.0
            ],
            [
              106.101,
              10.401,
              3.8,
              1790000150.0
            ],
            [
              106.1,
              10.401,
              4.0,
              1790000240.0
            ]
          ]
        }
      },
      "BoundaryWalkResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "polygon_sha256",
          "area_ha",
          "registered_area_ha",
          "area_difference_ratio",
          "points_total",
          "points_kept",
          "points_dropped",
          "superseded"
        ],
        "description": "#248: what a submitted walk answers; the same walk sent again answers the same.",
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1,
            "description": "The walk's id."
          },
          "polygon_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 (hex) of the outline's canonical GeoJSON text (compact, sorted keys, UTF-8): the SHA-256 of the boundary proposal the walk made, and of the version it becomes once a platform admin approves it."
          },
          "area_ha": {
            "type": "number",
            "description": "The walked area in hectares: the ring area on a sphere of the WGS 84 equatorial radius, as the admin console computes a boundary's area."
          },
          "registered_area_ha": {
            "type": [
              "number",
              "null"
            ],
            "description": "The growing area's registered `area_ha` when the walk was received."
          },
          "area_difference_ratio": {
            "type": [
              "number",
              "null"
            ],
            "description": "(area_ha - registered_area_ha) / registered_area_ha: negative when the walk found less than registered; null without a registered size."
          },
          "points_total": {
            "type": "integer",
            "minimum": 1,
            "description": "Fixes in the raw track."
          },
          "points_kept": {
            "type": "integer",
            "minimum": 0,
            "description": "Fixes whose accuracy is within the walk's threshold (they may back the outline)."
          },
          "points_dropped": {
            "type": "integer",
            "minimum": 0,
            "description": "Fixes less precise than the threshold (kept in the track, never in the outline)."
          },
          "superseded": {
            "type": "boolean",
            "description": "Whether the walk replaced a boundary proposal that was waiting."
          }
        },
        "example": {
          "id": 17,
          "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
          "area_ha": 1.2172891,
          "registered_area_ha": 2.0,
          "area_difference_ratio": -0.39135545,
          "points_total": 6,
          "points_kept": 5,
          "points_dropped": 1,
          "superseded": false
        }
      },
      "BoundaryWalkSummary": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "growing_area",
          "client_walk_id",
          "submitted_by",
          "submitted_at",
          "started_at",
          "finished_at",
          "accuracy_threshold_m",
          "polygon_sha256",
          "area_ha",
          "registered_area_ha",
          "area_difference_ratio",
          "points_total",
          "points_kept",
          "points_dropped",
          "superseded"
        ],
        "description": "#248: a walk kept as the evidence of a boundary proposal, without its track. It is the evidence of the proposal and of the boundary version with the same `polygon_sha256`.",
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1,
            "description": "The walk's id."
          },
          "growing_area": {
            "type": "string"
          },
          "client_walk_id": {
            "type": "string",
            "format": "uuid"
          },
          "submitted_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who sent the walk."
          },
          "submitted_at": {
            "type": "number",
            "description": "Unix seconds when the walk was received."
          },
          "started_at": {
            "type": "number",
            "description": "Unix seconds when the walk started (the phone's clock)."
          },
          "finished_at": {
            "type": "number",
            "description": "Unix seconds when the walk finished (the phone's clock)."
          },
          "accuracy_threshold_m": {
            "type": "number",
            "description": "The accuracy threshold of the walk in metres."
          },
          "polygon_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 (hex) of the outline's canonical GeoJSON text (compact, sorted keys, UTF-8): the SHA-256 of the boundary proposal the walk made, and of the version it becomes once a platform admin approves it."
          },
          "area_ha": {
            "type": "number",
            "description": "The walked area in hectares: the ring area on a sphere of the WGS 84 equatorial radius, as the admin console computes a boundary's area."
          },
          "registered_area_ha": {
            "type": [
              "number",
              "null"
            ],
            "description": "The growing area's registered `area_ha` when the walk was received."
          },
          "area_difference_ratio": {
            "type": [
              "number",
              "null"
            ],
            "description": "(area_ha - registered_area_ha) / registered_area_ha: negative when the walk found less than registered; null without a registered size."
          },
          "points_total": {
            "type": "integer",
            "minimum": 1,
            "description": "Fixes in the raw track."
          },
          "points_kept": {
            "type": "integer",
            "minimum": 0,
            "description": "Fixes whose accuracy is within the walk's threshold (they may back the outline)."
          },
          "points_dropped": {
            "type": "integer",
            "minimum": 0,
            "description": "Fixes less precise than the threshold (kept in the track, never in the outline)."
          },
          "superseded": {
            "type": "boolean",
            "description": "Whether the walk replaced a boundary proposal that was waiting."
          }
        },
        "example": {
          "id": 17,
          "growing_area": "VN-TGOR-0387",
          "client_walk_id": "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b",
          "submitted_by": "op@coop.example",
          "submitted_at": 1790000300.0,
          "started_at": 1790000000.0,
          "finished_at": 1790000240.0,
          "accuracy_threshold_m": 15.0,
          "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
          "area_ha": 1.2172891,
          "registered_area_ha": 2.0,
          "area_difference_ratio": -0.39135545,
          "points_total": 6,
          "points_kept": 5,
          "points_dropped": 1,
          "superseded": false
        }
      },
      "BoundaryWalk": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "growing_area",
          "client_walk_id",
          "submitted_by",
          "submitted_at",
          "started_at",
          "finished_at",
          "accuracy_threshold_m",
          "polygon_sha256",
          "area_ha",
          "registered_area_ha",
          "area_difference_ratio",
          "points_total",
          "points_kept",
          "points_dropped",
          "superseded",
          "polygon",
          "points"
        ],
        "description": "#248: one walk with its outline and its raw track.",
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1,
            "description": "The walk's id."
          },
          "growing_area": {
            "type": "string"
          },
          "client_walk_id": {
            "type": "string",
            "format": "uuid"
          },
          "submitted_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "Who sent the walk."
          },
          "submitted_at": {
            "type": "number",
            "description": "Unix seconds when the walk was received."
          },
          "started_at": {
            "type": "number",
            "description": "Unix seconds when the walk started (the phone's clock)."
          },
          "finished_at": {
            "type": "number",
            "description": "Unix seconds when the walk finished (the phone's clock)."
          },
          "accuracy_threshold_m": {
            "type": "number",
            "description": "The accuracy threshold of the walk in metres."
          },
          "polygon_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 (hex) of the outline's canonical GeoJSON text (compact, sorted keys, UTF-8): the SHA-256 of the boundary proposal the walk made, and of the version it becomes once a platform admin approves it."
          },
          "area_ha": {
            "type": "number",
            "description": "The walked area in hectares: the ring area on a sphere of the WGS 84 equatorial radius, as the admin console computes a boundary's area."
          },
          "registered_area_ha": {
            "type": [
              "number",
              "null"
            ],
            "description": "The growing area's registered `area_ha` when the walk was received."
          },
          "area_difference_ratio": {
            "type": [
              "number",
              "null"
            ],
            "description": "(area_ha - registered_area_ha) / registered_area_ha: negative when the walk found less than registered; null without a registered size."
          },
          "points_total": {
            "type": "integer",
            "minimum": 1,
            "description": "Fixes in the raw track."
          },
          "points_kept": {
            "type": "integer",
            "minimum": 0,
            "description": "Fixes whose accuracy is within the walk's threshold (they may back the outline)."
          },
          "points_dropped": {
            "type": "integer",
            "minimum": 0,
            "description": "Fixes less precise than the threshold (kept in the track, never in the outline)."
          },
          "superseded": {
            "type": "boolean",
            "description": "Whether the walk replaced a boundary proposal that was waiting."
          },
          "polygon": {
            "$ref": "#/components/schemas/GeoJsonPolygon"
          },
          "points": {
            "type": "array",
            "minItems": 1,
            "maxItems": 20000,
            "items": {
              "type": "array",
              "minItems": 4,
              "maxItems": 4,
              "items": {
                "type": "number"
              },
              "description": "[longitude, latitude, accuracy_m, time]: WGS 84 degrees, the fix's reported accuracy in metres (above 0, at most 10000) and Unix seconds (within 60 s of the walk's start and end)."
            },
            "description": "The raw track: every fix taken during the walk, the imprecise ones included, at most 20000 (and the whole body at most 1 MiB)."
          }
        },
        "example": {
          "id": 17,
          "growing_area": "VN-TGOR-0387",
          "client_walk_id": "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b",
          "submitted_by": "op@coop.example",
          "submitted_at": 1790000300.0,
          "started_at": 1790000000.0,
          "finished_at": 1790000240.0,
          "accuracy_threshold_m": 15.0,
          "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
          "area_ha": 1.2172891,
          "registered_area_ha": 2.0,
          "area_difference_ratio": -0.39135545,
          "points_total": 6,
          "points_kept": 5,
          "points_dropped": 1,
          "superseded": false,
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.101,
                  10.4
                ],
                [
                  106.101,
                  10.401
                ],
                [
                  106.1,
                  10.401
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          },
          "points": [
            [
              106.1,
              10.4,
              4.0,
              1790000000.0
            ],
            [
              106.1005,
              10.4,
              3.5,
              1790000030.0
            ],
            [
              106.1004,
              10.4003,
              32.0,
              1790000040.0
            ],
            [
              106.101,
              10.4,
              4.2,
              1790000060.0
            ],
            [
              106.101,
              10.401,
              3.8,
              1790000150.0
            ],
            [
              106.1,
              10.401,
              4.0,
              1790000240.0
            ]
          ]
        }
      },
      "BoundaryWalkPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/BoundaryWalkSummary"
            },
            "description": "Newest first."
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "items": [
            {
              "id": 17,
              "growing_area": "VN-TGOR-0387",
              "client_walk_id": "6f1c2a7e-3b4d-4e5f-8a9b-0c1d2e3f4a5b",
              "submitted_by": "op@coop.example",
              "submitted_at": 1790000300.0,
              "started_at": 1790000000.0,
              "finished_at": 1790000240.0,
              "accuracy_threshold_m": 15.0,
              "polygon_sha256": "5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e5d0e",
              "area_ha": 1.2172891,
              "registered_area_ha": 2.0,
              "area_difference_ratio": -0.39135545,
              "points_total": 6,
              "points_kept": 5,
              "points_dropped": 1,
              "superseded": false
            }
          ],
          "next_cursor": null
        }
      },
      "LandCertificateCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "central_meridian_min",
          "corners",
          "photo_sha256"
        ],
        "description": "#250: the parcel corners printed on a land-use right certificate's parcel map (VN-2000 plane coordinates) and the photo of the certificate page.",
        "properties": {
          "central_meridian_min": {
            "type": "integer",
            "minimum": 6180,
            "maximum": 6510,
            "description": "The central meridian of the parcel map's projection, in minutes of arc east of Greenwich (e.g. 6345 = 105 degrees 45 minutes): one of the provinces' central meridians of Circular 26/2024/TT-BTNMT Appendix 01."
          },
          "corners": {
            "type": "array",
            "minItems": 3,
            "maxItems": 201,
            "items": {
              "type": "array",
              "minItems": 2,
              "maxItems": 2,
              "items": {
                "type": "number"
              },
              "description": "[X, Y]: X the northing and Y the easting in metres, as the certificate prints them (X from 800000 to 2700000, Y from 200000 to 800000)."
            },
            "description": "The corners in order around the parcel, 3 to 200 (the first may be repeated at the end; it is dropped), at least 3 different."
          },
          "photo_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the photo of the certificate page, an image the company uploaded (`PUT /v1/attachments/{sha256}`): never public; read it with `GET /v1/attachments/{sha256}`."
          }
        },
        "example": {
          "central_meridian_min": 6345,
          "corners": [
            [
              1150116.67,
              538126.67
            ],
            [
              1150116.79,
              538236.17
            ],
            [
              1150227.39,
              538236.05
            ],
            [
              1150227.27,
              538126.55
            ]
          ],
          "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c"
        }
      },
      "LandCertificateCheck": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "central_meridian_min",
          "corners"
        ],
        "description": "#250: the parcel corners of a land-use right certificate to check before its photo is uploaded: LandCertificateCreate without `photo_sha256`.",
        "properties": {
          "central_meridian_min": {
            "type": "integer",
            "minimum": 6180,
            "maximum": 6510,
            "description": "The central meridian of the parcel map's projection, in minutes of arc east of Greenwich (e.g. 6345 = 105 degrees 45 minutes): one of the provinces' central meridians of Circular 26/2024/TT-BTNMT Appendix 01."
          },
          "corners": {
            "type": "array",
            "minItems": 3,
            "maxItems": 201,
            "items": {
              "type": "array",
              "minItems": 2,
              "maxItems": 2,
              "items": {
                "type": "number"
              },
              "description": "[X, Y]: X the northing and Y the easting in metres, as the certificate prints them (X from 800000 to 2700000, Y from 200000 to 800000)."
            },
            "description": "The corners in order around the parcel, 3 to 200 (the first may be repeated at the end; it is dropped), at least 3 different."
          }
        },
        "example": {
          "central_meridian_min": 6345,
          "corners": [
            [
              1150116.67,
              538126.67
            ],
            [
              1150116.79,
              538236.17
            ],
            [
              1150227.39,
              538236.05
            ],
            [
              1150227.27,
              538126.55
            ]
          ]
        }
      },
      "LandCertificateCheckResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "corners_total",
          "plane_area_m2",
          "polygon_sha256",
          "area_ha",
          "registered_area_ha",
          "area_difference_ratio",
          "polygon"
        ],
        "description": "#250: a passed check: the outline the certificate would propose, compared with the area's registered size. Nothing is stored.",
        "properties": {
          "corners_total": {
            "type": "integer",
            "minimum": 3,
            "maximum": 200,
            "description": "The number of corners."
          },
          "plane_area_m2": {
            "type": "number",
            "description": "The parcel's area in square metres on the projection plane, from the corners as typed: the figure a certificate prints, so a typing slip shows."
          },
          "polygon_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 (hex) of the converted outline's canonical GeoJSON text (compact, sorted keys, UTF-8): the SHA-256 of the boundary proposal the certificate made, and of the version it becomes once a platform admin approves it."
          },
          "area_ha": {
            "type": "number",
            "description": "The converted outline's area in hectares: the ring area on a sphere of the WGS 84 equatorial radius, as the admin console and the boundary walks compute a boundary's area."
          },
          "registered_area_ha": {
            "type": [
              "number",
              "null"
            ],
            "description": "The growing area's registered `area_ha` when the certificate was received."
          },
          "area_difference_ratio": {
            "type": [
              "number",
              "null"
            ],
            "description": "(area_ha - registered_area_ha) / registered_area_ha: negative when the certificate's parcel is smaller than registered; null without a registered size."
          },
          "polygon": {
            "$ref": "#/components/schemas/GeoJsonPolygon"
          }
        },
        "example": {
          "corners_total": 4,
          "plane_area_m2": 12110.71,
          "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
          "area_ha": 1.2188975,
          "registered_area_ha": 2.0,
          "area_difference_ratio": -0.39055124,
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.09999996,
                  10.39999998
                ],
                [
                  106.10100002,
                  10.39999997
                ],
                [
                  106.10100004,
                  10.40099996
                ],
                [
                  106.09999998,
                  10.40099996
                ],
                [
                  106.09999996,
                  10.39999998
                ]
              ]
            ]
          }
        }
      },
      "LandCertificateWalkComparison": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "walk_id",
          "area_ha",
          "area_difference_ratio",
          "centre_offset_m"
        ],
        "description": "#250: a certificate against the area's latest boundary walk (#248).",
        "properties": {
          "walk_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The walk's id."
          },
          "area_ha": {
            "type": "number",
            "description": "The walked area in hectares."
          },
          "area_difference_ratio": {
            "type": [
              "number",
              "null"
            ],
            "description": "(certificate area - walked area) / walked area."
          },
          "centre_offset_m": {
            "type": [
              "number",
              "null"
            ],
            "description": "The distance in metres between the centres of the two outlines (a local approximation, to compare, not a survey)."
          }
        },
        "example": {
          "walk_id": 17,
          "area_ha": 1.2172891,
          "area_difference_ratio": 0.00132129,
          "centre_offset_m": 0.02
        }
      },
      "LandCertificateSummary": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "growing_area",
          "submitted_at",
          "central_meridian_min",
          "corners_total",
          "plane_area_m2",
          "photo_sha256",
          "polygon_sha256",
          "area_ha",
          "registered_area_ha",
          "area_difference_ratio",
          "walk",
          "superseded"
        ],
        "description": "#250: a land certificate kept as the evidence of a boundary proposal, without its corners. It is the evidence of the proposal and of the boundary version with the same `polygon_sha256`: that boundary is \"from land certificate\".",
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1,
            "description": "The certificate's id."
          },
          "growing_area": {
            "type": "string"
          },
          "submitted_at": {
            "type": "number",
            "description": "Unix seconds when the certificate was received."
          },
          "central_meridian_min": {
            "type": "integer",
            "minimum": 6180,
            "maximum": 6510,
            "description": "The central meridian of the parcel map's projection, in minutes of arc east of Greenwich (e.g. 6345 = 105 degrees 45 minutes): one of the provinces' central meridians of Circular 26/2024/TT-BTNMT Appendix 01."
          },
          "corners_total": {
            "type": "integer",
            "minimum": 3,
            "maximum": 200,
            "description": "The number of corners."
          },
          "plane_area_m2": {
            "type": "number",
            "description": "The parcel's area in square metres on the projection plane, from the corners as typed: the figure a certificate prints, so a typing slip shows."
          },
          "photo_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the photo of the certificate page, an image the company uploaded (`PUT /v1/attachments/{sha256}`): never public; read it with `GET /v1/attachments/{sha256}`."
          },
          "polygon_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 (hex) of the converted outline's canonical GeoJSON text (compact, sorted keys, UTF-8): the SHA-256 of the boundary proposal the certificate made, and of the version it becomes once a platform admin approves it."
          },
          "area_ha": {
            "type": "number",
            "description": "The converted outline's area in hectares: the ring area on a sphere of the WGS 84 equatorial radius, as the admin console and the boundary walks compute a boundary's area."
          },
          "registered_area_ha": {
            "type": [
              "number",
              "null"
            ],
            "description": "The growing area's registered `area_ha` when the certificate was received."
          },
          "area_difference_ratio": {
            "type": [
              "number",
              "null"
            ],
            "description": "(area_ha - registered_area_ha) / registered_area_ha: negative when the certificate's parcel is smaller than registered; null without a registered size."
          },
          "walk": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/LandCertificateWalkComparison"
              },
              {
                "type": "null"
              }
            ],
            "description": "The certificate against the area's latest boundary walk; null when the area has none."
          },
          "superseded": {
            "type": "boolean",
            "description": "Whether the certificate replaced a boundary proposal that was waiting."
          }
        },
        "example": {
          "id": 5,
          "growing_area": "VN-TGOR-0387",
          "submitted_at": 1790000300.0,
          "central_meridian_min": 6345,
          "corners_total": 4,
          "plane_area_m2": 12110.71,
          "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c",
          "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
          "area_ha": 1.2188975,
          "registered_area_ha": 2.0,
          "area_difference_ratio": -0.39055124,
          "walk": {
            "walk_id": 17,
            "area_ha": 1.2172891,
            "area_difference_ratio": 0.00132129,
            "centre_offset_m": 0.02
          },
          "superseded": false
        }
      },
      "LandCertificate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "growing_area",
          "submitted_at",
          "central_meridian_min",
          "corners_total",
          "plane_area_m2",
          "photo_sha256",
          "polygon_sha256",
          "area_ha",
          "registered_area_ha",
          "area_difference_ratio",
          "walk",
          "superseded",
          "corners",
          "polygon"
        ],
        "description": "#250: one land certificate with the corners as typed and the converted outline (WGS 84).",
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1,
            "description": "The certificate's id."
          },
          "growing_area": {
            "type": "string"
          },
          "submitted_at": {
            "type": "number",
            "description": "Unix seconds when the certificate was received."
          },
          "central_meridian_min": {
            "type": "integer",
            "minimum": 6180,
            "maximum": 6510,
            "description": "The central meridian of the parcel map's projection, in minutes of arc east of Greenwich (e.g. 6345 = 105 degrees 45 minutes): one of the provinces' central meridians of Circular 26/2024/TT-BTNMT Appendix 01."
          },
          "corners_total": {
            "type": "integer",
            "minimum": 3,
            "maximum": 200,
            "description": "The number of corners."
          },
          "plane_area_m2": {
            "type": "number",
            "description": "The parcel's area in square metres on the projection plane, from the corners as typed: the figure a certificate prints, so a typing slip shows."
          },
          "photo_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the photo of the certificate page, an image the company uploaded (`PUT /v1/attachments/{sha256}`): never public; read it with `GET /v1/attachments/{sha256}`."
          },
          "polygon_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 (hex) of the converted outline's canonical GeoJSON text (compact, sorted keys, UTF-8): the SHA-256 of the boundary proposal the certificate made, and of the version it becomes once a platform admin approves it."
          },
          "area_ha": {
            "type": "number",
            "description": "The converted outline's area in hectares: the ring area on a sphere of the WGS 84 equatorial radius, as the admin console and the boundary walks compute a boundary's area."
          },
          "registered_area_ha": {
            "type": [
              "number",
              "null"
            ],
            "description": "The growing area's registered `area_ha` when the certificate was received."
          },
          "area_difference_ratio": {
            "type": [
              "number",
              "null"
            ],
            "description": "(area_ha - registered_area_ha) / registered_area_ha: negative when the certificate's parcel is smaller than registered; null without a registered size."
          },
          "walk": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/LandCertificateWalkComparison"
              },
              {
                "type": "null"
              }
            ],
            "description": "The certificate against the area's latest boundary walk; null when the area has none."
          },
          "superseded": {
            "type": "boolean",
            "description": "Whether the certificate replaced a boundary proposal that was waiting."
          },
          "corners": {
            "type": "array",
            "minItems": 3,
            "maxItems": 200,
            "items": {
              "type": "array",
              "minItems": 2,
              "maxItems": 2,
              "items": {
                "type": "number"
              }
            },
            "description": "The corners [X, Y] (VN-2000, metres) as typed, without a repeated first corner."
          },
          "polygon": {
            "$ref": "#/components/schemas/GeoJsonPolygon"
          }
        },
        "example": {
          "id": 5,
          "growing_area": "VN-TGOR-0387",
          "submitted_at": 1790000300.0,
          "central_meridian_min": 6345,
          "corners_total": 4,
          "plane_area_m2": 12110.71,
          "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c",
          "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
          "area_ha": 1.2188975,
          "registered_area_ha": 2.0,
          "area_difference_ratio": -0.39055124,
          "walk": {
            "walk_id": 17,
            "area_ha": 1.2172891,
            "area_difference_ratio": 0.00132129,
            "centre_offset_m": 0.02
          },
          "superseded": false,
          "corners": [
            [
              1150116.67,
              538126.67
            ],
            [
              1150116.79,
              538236.17
            ],
            [
              1150227.39,
              538236.05
            ],
            [
              1150227.27,
              538126.55
            ]
          ],
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.09999996,
                  10.39999998
                ],
                [
                  106.10100002,
                  10.39999997
                ],
                [
                  106.10100004,
                  10.40099996
                ],
                [
                  106.09999998,
                  10.40099996
                ],
                [
                  106.09999996,
                  10.39999998
                ]
              ]
            ]
          }
        }
      },
      "LandCertificatePage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LandCertificateSummary"
            },
            "description": "Newest first."
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "items": [
            {
              "id": 5,
              "growing_area": "VN-TGOR-0387",
              "submitted_at": 1790000300.0,
              "central_meridian_min": 6345,
              "corners_total": 4,
              "plane_area_m2": 12110.71,
              "photo_sha256": "3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c3f9c",
              "polygon_sha256": "8ba5874c1392fdd1261f2be94e4ecc813d585bc485a4d066711e7afdf41d681e",
              "area_ha": 1.2188975,
              "registered_area_ha": 2.0,
              "area_difference_ratio": -0.39055124,
              "walk": {
                "walk_id": 17,
                "area_ha": 1.2172891,
                "area_difference_ratio": 0.00132129,
                "centre_offset_m": 0.02
              },
              "superseded": false
            }
          ],
          "next_cursor": null
        }
      },
      "SensorSeriesBucket": {
        "type": "object",
        "description": "SENS-B1e (#235): one hourly or daily bucket of a sensor series, as the summary of the reading record stores it. The statistics take only the readings flagged pass or not evaluated that have a value; every reading counts in `n_total` and in its flag's count (QARTOD flags: 1 pass, 2 not evaluated, 3 suspect, 4 fail, 9 missing).",
        "additionalProperties": false,
        "required": [
          "bucket_start",
          "min",
          "max",
          "mean",
          "count",
          "n_total",
          "n_pass",
          "n_not_evaluated",
          "n_suspect",
          "n_fail",
          "n_missing"
        ],
        "properties": {
          "bucket_start": {
            "type": "number",
            "description": "Start of the UTC hour or day, or (`local_daily`) of the farm day: its local midnight. Unix seconds."
          },
          "min": {
            "type": [
              "number",
              "null"
            ],
            "description": "Null when `count` is 0."
          },
          "max": {
            "type": [
              "number",
              "null"
            ],
            "description": "Null when `count` is 0."
          },
          "mean": {
            "type": [
              "number",
              "null"
            ],
            "description": "The sum of the values over `count`; null when `count` is 0."
          },
          "count": {
            "type": "integer",
            "minimum": 0,
            "description": "Values in the statistics."
          },
          "n_total": {
            "type": "integer",
            "minimum": 0,
            "description": "Every reading of the bucket."
          },
          "n_pass": {
            "type": "integer",
            "minimum": 0,
            "description": "Readings flagged 1 (pass)."
          },
          "n_not_evaluated": {
            "type": "integer",
            "minimum": 0,
            "description": "Readings flagged 2 (not evaluated)."
          },
          "n_suspect": {
            "type": "integer",
            "minimum": 0,
            "description": "Readings flagged 3 (suspect)."
          },
          "n_fail": {
            "type": "integer",
            "minimum": 0,
            "description": "Readings flagged 4 (fail)."
          },
          "n_missing": {
            "type": "integer",
            "minimum": 0,
            "description": "Readings flagged 9 (missing value)."
          }
        },
        "example": {
          "bucket_start": 1790726400.0,
          "min": 30.7,
          "max": 31.1,
          "mean": 30.9,
          "count": 2,
          "n_total": 3,
          "n_pass": 2,
          "n_not_evaluated": 0,
          "n_suspect": 0,
          "n_fail": 0,
          "n_missing": 1
        }
      },
      "SensorSeriesDepth": {
        "type": "object",
        "description": "SENS-B1e (#235): the buckets of one depth, oldest first.",
        "additionalProperties": false,
        "required": [
          "depth_cm",
          "buckets"
        ],
        "properties": {
          "depth_cm": {
            "type": [
              "number",
              "null"
            ],
            "description": "The readings' depth in cm; null for readings without a depth."
          },
          "buckets": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SensorSeriesBucket"
            }
          }
        },
        "example": {
          "depth_cm": 10.0,
          "buckets": [
            {
              "bucket_start": 1790726400.0,
              "min": 30.7,
              "max": 31.1,
              "mean": 30.9,
              "count": 2,
              "n_total": 3,
              "n_pass": 2,
              "n_not_evaluated": 0,
              "n_suspect": 0,
              "n_fail": 0,
              "n_missing": 1
            },
            {
              "bucket_start": 1790730000.0,
              "min": null,
              "max": null,
              "mean": null,
              "count": 0,
              "n_total": 1,
              "n_pass": 0,
              "n_not_evaluated": 0,
              "n_suspect": 0,
              "n_fail": 1,
              "n_missing": 0
            }
          ]
        }
      },
      "SensorSeries": {
        "type": "object",
        "description": "SENS-B1e (#235): the hourly, daily (UTC) or farm-day (`local_daily`, #365) summaries of one capability in a growing area, from the caller's company's devices only, one series per depth (no depth first, then ascending).",
        "additionalProperties": false,
        "required": [
          "growing_area",
          "capability",
          "unit",
          "grain",
          "bucket_s",
          "from",
          "to",
          "truncated",
          "series"
        ],
        "properties": {
          "growing_area": {
            "type": "string"
          },
          "capability": {
            "type": "string"
          },
          "unit": {
            "type": [
              "string",
              "null"
            ],
            "description": "The vocabulary's UCUM unit of the capability."
          },
          "grain": {
            "type": "string",
            "enum": [
              "hourly",
              "daily",
              "local_daily"
            ]
          },
          "bucket_s": {
            "type": "number",
            "description": "Bucket width in seconds: 3600 or 86400."
          },
          "from": {
            "type": "number",
            "description": "Start of the range, Unix seconds."
          },
          "to": {
            "type": "number",
            "description": "End of the range (excluded), Unix seconds."
          },
          "truncated": {
            "type": "boolean",
            "description": "True when the answer reached the bucket cap (5000 buckets in all): the later depths or buckets were left out."
          },
          "series": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SensorSeriesDepth"
            }
          },
          "time_zone": {
            "type": "string",
            "enum": [
              "Asia/Ho_Chi_Minh"
            ],
            "description": "`local_daily` only: the farm time zone whose days the buckets are."
          },
          "day_starts_at": {
            "type": "number",
            "description": "`local_daily` only: the local midnight (Unix seconds) that starts the farm day holding `from`, the first bucket a day may have."
          }
        },
        "example": {
          "growing_area": "VN-TGOR-0387",
          "capability": "soil.moisture",
          "unit": "%",
          "grain": "hourly",
          "bucket_s": 3600.0,
          "from": 1790125200.0,
          "to": 1790730000.0,
          "truncated": false,
          "series": [
            {
              "depth_cm": 10.0,
              "buckets": [
                {
                  "bucket_start": 1790726400.0,
                  "min": 30.7,
                  "max": 31.1,
                  "mean": 30.9,
                  "count": 2,
                  "n_total": 3,
                  "n_pass": 2,
                  "n_not_evaluated": 0,
                  "n_suspect": 0,
                  "n_fail": 0,
                  "n_missing": 1
                },
                {
                  "bucket_start": 1790730000.0,
                  "min": null,
                  "max": null,
                  "mean": null,
                  "count": 0,
                  "n_total": 1,
                  "n_pass": 0,
                  "n_not_evaluated": 0,
                  "n_suspect": 0,
                  "n_fail": 1,
                  "n_missing": 0
                }
              ]
            }
          ]
        }
      },
      "VerdictCounts": {
        "type": "object",
        "description": "SENS-B1e (#235): how many positions of the device got each geofence verdict in the range.",
        "additionalProperties": false,
        "required": [
          "inside",
          "near",
          "outside",
          "ambiguous",
          "unverifiable",
          "no_position",
          "no_polygon"
        ],
        "properties": {
          "inside": {
            "type": "integer",
            "minimum": 0
          },
          "near": {
            "type": "integer",
            "minimum": 0
          },
          "outside": {
            "type": "integer",
            "minimum": 0
          },
          "ambiguous": {
            "type": "integer",
            "minimum": 0
          },
          "unverifiable": {
            "type": "integer",
            "minimum": 0
          },
          "no_position": {
            "type": "integer",
            "minimum": 0
          },
          "no_polygon": {
            "type": "integer",
            "minimum": 0
          }
        },
        "example": {
          "inside": 41,
          "near": 2,
          "outside": 1,
          "ambiguous": 0,
          "unverifiable": 0,
          "no_position": 0,
          "no_polygon": 0
        }
      },
      "MapPoint": {
        "type": "object",
        "description": "SENS-B1e (#235): a placement's surveyed install point (WGS84).",
        "additionalProperties": false,
        "required": [
          "lat",
          "lon",
          "accuracy_m"
        ],
        "properties": {
          "lat": {
            "type": "number"
          },
          "lon": {
            "type": "number"
          },
          "accuracy_m": {
            "type": "number"
          }
        },
        "example": {
          "lat": 10.45,
          "lon": 106.15,
          "accuracy_m": 2.0
        }
      },
      "JudgedPosition": {
        "type": "object",
        "description": "SENS-B1e (#235): the latest position of the device judged against the area in the range (WGS84, as the device signed it), with its verdict and when ingest judged it.",
        "additionalProperties": false,
        "required": [
          "lat",
          "lon",
          "acc_m",
          "verdict",
          "checked_at"
        ],
        "properties": {
          "lat": {
            "type": "number"
          },
          "lon": {
            "type": "number"
          },
          "acc_m": {
            "type": [
              "number",
              "null"
            ],
            "description": "The accuracy the device reported; null when it reported none."
          },
          "verdict": {
            "$ref": "#/components/schemas/GeofenceVerdict"
          },
          "checked_at": {
            "type": "number"
          }
        },
        "example": {
          "lat": 10.4501,
          "lon": 106.1502,
          "acc_m": 3.0,
          "verdict": "inside",
          "checked_at": 1790726400.0
        }
      },
      "GeofenceVerdict": {
        "type": "string",
        "description": "SENS-B1e (#235): a geofence verdict of a position against a growing area's boundary.",
        "enum": [
          "inside",
          "near",
          "outside",
          "ambiguous",
          "unverifiable",
          "no_position",
          "no_polygon"
        ],
        "example": "inside"
      },
      "VerdictMapPlacement": {
        "type": "object",
        "description": "SENS-B1e (#235): the device's current placement version.",
        "additionalProperties": false,
        "required": [
          "version",
          "mobility",
          "growing_area",
          "bound_here",
          "depth_cm",
          "installed_at",
          "removed_at"
        ],
        "properties": {
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "mobility": {
            "type": "string",
            "enum": [
              "fixed",
              "mobile"
            ]
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ],
            "description": "The area the version binds the device to."
          },
          "bound_here": {
            "type": "boolean",
            "description": "The version is an installation bound to this area."
          },
          "depth_cm": {
            "type": [
              "number",
              "null"
            ]
          },
          "installed_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "removed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Set when the current version is a removal."
          },
          "install_point": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/MapPoint"
              },
              {
                "type": "null"
              }
            ],
            "description": "Present only when `coordinates_shown` (a platform admin, or an operator or admin of the area's owning company); never public. Null for a version without one."
          }
        },
        "example": {
          "version": 1,
          "mobility": "fixed",
          "growing_area": "VN-TGOR-0387",
          "bound_here": true,
          "depth_cm": 30.0,
          "installed_at": 1790000000.0,
          "removed_at": null,
          "install_point": {
            "lat": 10.45,
            "lon": 106.15,
            "accuracy_m": 2.0
          }
        }
      },
      "VerdictMapDevice": {
        "type": "object",
        "description": "SENS-B1e (#235): one device of the caller's company bound to the area or judged against it in the range.",
        "additionalProperties": false,
        "required": [
          "device_id",
          "profile",
          "placement",
          "verdict_counts",
          "latest_verdict",
          "latest_verdict_at"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "profile": {
            "type": "string"
          },
          "placement": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/VerdictMapPlacement"
              },
              {
                "type": "null"
              }
            ],
            "description": "Null for a device without a placement."
          },
          "verdict_counts": {
            "$ref": "#/components/schemas/VerdictCounts"
          },
          "latest_verdict": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeofenceVerdict"
              },
              {
                "type": "null"
              }
            ]
          },
          "latest_verdict_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When ingest judged the latest position (its reception)."
          },
          "latest_position": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/JudgedPosition"
              },
              {
                "type": "null"
              }
            ],
            "description": "Present only when `coordinates_shown` (a platform admin, or an operator or admin of the area's owning company); never public. Null when no position was judged in the range."
          }
        },
        "example": {
          "device_id": "knk-1",
          "profile": "vn.agritrace.durian-knocker",
          "placement": {
            "version": 1,
            "mobility": "fixed",
            "growing_area": "VN-TGOR-0387",
            "bound_here": true,
            "depth_cm": 30.0,
            "installed_at": 1790000000.0,
            "removed_at": null,
            "install_point": {
              "lat": 10.45,
              "lon": 106.15,
              "accuracy_m": 2.0
            }
          },
          "verdict_counts": {
            "inside": 41,
            "near": 2,
            "outside": 1,
            "ambiguous": 0,
            "unverifiable": 0,
            "no_position": 0,
            "no_polygon": 0
          },
          "latest_verdict": "inside",
          "latest_verdict_at": 1790726400.0,
          "latest_position": {
            "lat": 10.4501,
            "lon": 106.1502,
            "acc_m": 3.0,
            "verdict": "inside",
            "checked_at": 1790726400.0
          }
        }
      },
      "VerdictMap": {
        "type": "object",
        "description": "SENS-B1e (#235): the growing area's devices with their geofence verdicts over a range of reception times.",
        "additionalProperties": false,
        "required": [
          "growing_area",
          "from",
          "to",
          "coordinates_shown",
          "truncated",
          "devices"
        ],
        "properties": {
          "growing_area": {
            "type": "string"
          },
          "from": {
            "type": "number",
            "description": "Start of the range of reception times, Unix seconds."
          },
          "to": {
            "type": "number",
            "description": "End of the range (included), Unix seconds."
          },
          "coordinates_shown": {
            "type": "boolean",
            "description": "Whether the install points and judged positions are given to this caller."
          },
          "truncated": {
            "type": "boolean",
            "description": "True when more than 500 devices matched: the rest, by device id, were left out."
          },
          "devices": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/VerdictMapDevice"
            },
            "description": "Ordered by device id."
          },
          "polygon": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/GeoJsonPolygon"
              },
              {
                "type": "null"
              }
            ],
            "description": "The area's boundary, present only for the owning tenant_admin and platform_admin (as the growing-area read); null: no boundary."
          }
        },
        "example": {
          "growing_area": "VN-TGOR-0387",
          "from": 1790121600.0,
          "to": 1790726400.0,
          "coordinates_shown": true,
          "truncated": false,
          "devices": [
            {
              "device_id": "knk-1",
              "profile": "vn.agritrace.durian-knocker",
              "placement": {
                "version": 1,
                "mobility": "fixed",
                "growing_area": "VN-TGOR-0387",
                "bound_here": true,
                "depth_cm": 30.0,
                "installed_at": 1790000000.0,
                "removed_at": null,
                "install_point": {
                  "lat": 10.45,
                  "lon": 106.15,
                  "accuracy_m": 2.0
                }
              },
              "verdict_counts": {
                "inside": 41,
                "near": 2,
                "outside": 1,
                "ambiguous": 0,
                "unverifiable": 0,
                "no_position": 0,
                "no_polygon": 0
              },
              "latest_verdict": "inside",
              "latest_verdict_at": 1790726400.0,
              "latest_position": {
                "lat": 10.4501,
                "lon": 106.1502,
                "acc_m": 3.0,
                "verdict": "inside",
                "checked_at": 1790726400.0
              }
            }
          ],
          "polygon": {
            "type": "Polygon",
            "coordinates": [
              [
                [
                  106.1,
                  10.4
                ],
                [
                  106.2,
                  10.4
                ],
                [
                  106.2,
                  10.5
                ],
                [
                  106.1,
                  10.5
                ],
                [
                  106.1,
                  10.4
                ]
              ]
            ]
          }
        }
      },
      "LocationCheck": {
        "type": "object",
        "description": "#247 (getAreaLocationCheck): which location check ingest makes now for the company's positions of this area, and the area's commune by point. A position is checked against the area's approved plot boundary when it has one in force (`plot_boundary`); else, once the platform imported commune boundaries (OpenStreetMap, ODbL 1.0), against the area's registered commune (`commune`: an alert on a mismatch, never a hold, and the location trust is unchanged); else not at all (`none`: no plot boundary and either no commune boundaries imported or an area not approved yet). A registered commune no unit of the boundary data is named like (`name` `unmatched`, e.g. a name from before the 2025-07-01 reform) gets only `commune_unknown`; `position_communes` then shows the post-2025 units the area's positions fell in, to change the area's commune to.",
        "additionalProperties": false,
        "required": [
          "applies",
          "registered_commune",
          "dataset",
          "name",
          "commune_verdict_counts",
          "position_communes",
          "attribution",
          "copyright"
        ],
        "properties": {
          "applies": {
            "type": "string",
            "enum": [
              "plot_boundary",
              "commune",
              "none"
            ],
            "description": "The check ingest makes now for a position of the area."
          },
          "registered_commune": {
            "type": [
              "string",
              "null"
            ],
            "description": "The commune registered on the area; null: none."
          },
          "dataset": {
            "type": [
              "string",
              "null"
            ],
            "description": "The key of the commune boundary dataset in force (the one imported last); null: none imported."
          },
          "name": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "matched",
              "unmatched",
              "missing",
              null
            ],
            "description": "Whether a unit of the dataset in force is named like the registered commune (`missing`: no commune registered); null without a dataset."
          },
          "commune_verdict_counts": {
            "$ref": "#/components/schemas/CommuneVerdictCounts"
          },
          "position_communes": {
            "anyOf": [
              {
                "type": "array",
                "maxItems": 5,
                "items": {
                  "$ref": "#/components/schemas/PositionCommune"
                }
              },
              {
                "type": "null"
              }
            ],
            "description": "The units of the dataset in force that contained the area's judged positions in the range, most first (at most 5); null without a dataset or when the caller is not given positions (only a platform admin and the owning company's operators and admins are)."
          },
          "attribution": {
            "type": [
              "string",
              "null"
            ],
            "description": "\"© OpenStreetMap contributors\", to show with any commune named here (ODbL); null without a dataset."
          },
          "copyright": {
            "type": [
              "string",
              "null"
            ],
            "description": "The OpenStreetMap copyright page the attribution links to; null without a dataset."
          }
        },
        "example": {
          "applies": "commune",
          "registered_commune": "Long Trung",
          "dataset": "osm-2026-10-15T20:21:00Z",
          "name": "unmatched",
          "commune_verdict_counts": {
            "commune_match": 0,
            "commune_mismatch": 0,
            "commune_unknown": 12
          },
          "position_communes": [
            {
              "name": "Xã Mẫu Một",
              "osm_relation": 101,
              "positions": 12
            }
          ],
          "attribution": "© OpenStreetMap contributors",
          "copyright": "https://www.openstreetmap.org/copyright"
        }
      },
      "CommuneVerdictCounts": {
        "type": "object",
        "description": "How many of the company's positions of the area in the range got each commune verdict (#247).",
        "additionalProperties": false,
        "required": [
          "commune_match",
          "commune_mismatch",
          "commune_unknown"
        ],
        "properties": {
          "commune_match": {
            "type": "integer",
            "minimum": 0
          },
          "commune_mismatch": {
            "type": "integer",
            "minimum": 0
          },
          "commune_unknown": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "PositionCommune": {
        "type": "object",
        "description": "#247: a commune-level unit of the boundary data that contained some of the area's judged positions.",
        "additionalProperties": false,
        "required": [
          "name",
          "osm_relation",
          "positions"
        ],
        "properties": {
          "name": {
            "type": "string",
            "description": "The unit's name in OpenStreetMap."
          },
          "osm_relation": {
            "type": "integer",
            "minimum": 1,
            "description": "The unit's OpenStreetMap relation id."
          },
          "positions": {
            "type": "integer",
            "minimum": 1,
            "description": "How many of the area's judged positions in the range it contained."
          }
        }
      },
      "CalibrationCertificate": {
        "type": "object",
        "description": "SENS-B1d (#234): a calibration certificate sent with the calibration. Its bytes must hash to the calibration's `certificate_sha256`; it is then kept as an upload of the company, as one sent with PUT /v1/attachments/{sha256} would be.",
        "additionalProperties": false,
        "required": [
          "media_type",
          "content_base64"
        ],
        "properties": {
          "media_type": {
            "type": "string",
            "enum": [
              "application/pdf",
              "image/jpeg",
              "image/png"
            ]
          },
          "content_base64": {
            "type": "string",
            "minLength": 1,
            "description": "The certificate's bytes, standard base64 (RFC 4648 §4, with padding), at most 1 MiB decoded (and within the 1 MiB request body)."
          }
        },
        "example": {
          "media_type": "application/pdf",
          "content_base64": "JVBERi0xLjQK"
        }
      },
      "CalibrationCreate": {
        "type": "object",
        "description": "SENS-B1d (#234): a calibration of a device of the company (GLOBALG.A.P. IFA v6 FV-GFS 13.01: measuring equipment calibrated at least yearly, traceably). Times are Unix seconds: `calibrated_at` from 2020-01-01 and at most 300 s ahead of the server clock, `valid_until` after it and at most about five years (5 × 366 days) later. The certificate is either uploaded first with PUT /v1/attachments/{sha256} for the same company (a PDF, JPEG or PNG) and named by `certificate_sha256`, or sent in `certificate` with `certificate_sha256`, which its bytes must hash to. A correction is a new calibration naming the one it corrects in `supersedes`; nothing is ever edited.",
        "additionalProperties": false,
        "required": [
          "calibrated_at",
          "method",
          "performer",
          "accreditation",
          "valid_until"
        ],
        "properties": {
          "sensor_serial": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100,
            "description": "The serial of the probe calibrated, when the device carries several."
          },
          "capability": {
            "type": "string",
            "minLength": 1,
            "maxLength": 128,
            "description": "The capability the calibration covers: one of the vocabulary's, or an `x-` extension. Absent: every capability of the device."
          },
          "calibrated_at": {
            "type": "number",
            "minimum": 1577836800,
            "description": "When the calibration was done."
          },
          "method": {
            "type": "string",
            "enum": [
              "ph_buffers",
              "ec_reference",
              "lab_correlation",
              "factory",
              "other"
            ],
            "description": "`ph_buffers`: pH buffer solutions (e.g. 4, 7 and 10); `ec_reference`: an EC reference solution; `lab_correlation`: against a laboratory analysis; `factory`: the manufacturer's calibration; `other`."
          },
          "reference_values": {
            "type": [
              "object",
              "array"
            ],
            "description": "The reference values used (e.g. the buffers' pH): a JSON object or array of at most 4096 bytes, nested at most 4 deep, finite numbers only, strings of at most 200 characters."
          },
          "coefficients": {
            "type": [
              "object",
              "array"
            ],
            "description": "The coefficients found (e.g. slope and offset), with the same bounds as `reference_values`."
          },
          "performer": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Who calibrated: a laboratory, a technician or the manufacturer."
          },
          "accreditation": {
            "type": "string",
            "enum": [
              "iso17025_lab",
              "in_house",
              "manufacturer"
            ],
            "description": "`iso17025_lab`: a laboratory accredited to ISO/IEC 17025; `in_house`: the company itself; `manufacturer`."
          },
          "certificate_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the calibration certificate (PDF, JPEG or PNG)."
          },
          "certificate": {
            "$ref": "#/components/schemas/CalibrationCertificate"
          },
          "valid_until": {
            "type": "number",
            "minimum": 1577836800,
            "description": "Until when the calibration is valid: after `calibrated_at`. A reading made later, while this calibration is the device's latest, is flagged suspect (`calibration_expired`)."
          },
          "supersedes": {
            "type": "integer",
            "minimum": 1,
            "description": "The id of a calibration of the same device that this one corrects; a calibration is superseded once at most."
          }
        },
        "example": {
          "sensor_serial": "RS485-4IN1-00172",
          "capability": "soil.ph",
          "calibrated_at": 1790000000.0,
          "method": "ph_buffers",
          "reference_values": {
            "buffers_ph": [
              4.01,
              7.0,
              10.01
            ]
          },
          "coefficients": {
            "offset": -0.03,
            "slope": 0.987
          },
          "performer": "Can Tho soil laboratory",
          "accreditation": "iso17025_lab",
          "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
          "valid_until": 1805552000.0
        }
      },
      "Calibration": {
        "type": "object",
        "description": "SENS-B1d (#234): a calibration record of a device, never changed once recorded. Ingest links each reading of the device to the calibration in force at its time (`calibration_id` of the reading record): the latest not superseded, made at or before the reading, covering the reading's capability or every capability of the device; when its `valid_until` is before the reading, the reading is flagged suspect (QC flag 3, reason `calibration_expired`).",
        "additionalProperties": false,
        "required": [
          "id",
          "device_id",
          "sensor_serial",
          "capability",
          "calibrated_at",
          "method",
          "reference_values",
          "coefficients",
          "performer",
          "accreditation",
          "certificate_sha256",
          "valid_until",
          "supersedes",
          "created_at",
          "superseded_by"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "device_id": {
            "type": "string"
          },
          "sensor_serial": {
            "type": [
              "string",
              "null"
            ]
          },
          "capability": {
            "type": [
              "string",
              "null"
            ],
            "description": "The capability covered; null: every capability of the device."
          },
          "calibrated_at": {
            "type": "number"
          },
          "method": {
            "type": "string",
            "enum": [
              "ph_buffers",
              "ec_reference",
              "lab_correlation",
              "factory",
              "other"
            ]
          },
          "reference_values": {
            "type": [
              "object",
              "array",
              "null"
            ]
          },
          "coefficients": {
            "type": [
              "object",
              "array",
              "null"
            ]
          },
          "performer": {
            "type": "string"
          },
          "accreditation": {
            "type": "string",
            "enum": [
              "iso17025_lab",
              "in_house",
              "manufacturer"
            ]
          },
          "certificate_sha256": {
            "type": [
              "string",
              "null"
            ],
            "description": "SHA-256 of the certificate, readable with GET /v1/attachments/{sha256}."
          },
          "valid_until": {
            "type": "number"
          },
          "supersedes": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The calibration this one corrects."
          },
          "created_at": {
            "type": "number"
          },
          "created_by": {
            "type": "string",
            "description": "Who recorded it; present for platform admins only."
          },
          "superseded_by": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The calibration that corrects this one; null while it is not corrected."
          }
        },
        "example": {
          "id": 12,
          "device_id": "soil-07",
          "sensor_serial": "RS485-4IN1-00172",
          "capability": "soil.ph",
          "calibrated_at": 1790000000.0,
          "method": "ph_buffers",
          "reference_values": {
            "buffers_ph": [
              4.01,
              7.0,
              10.01
            ]
          },
          "coefficients": {
            "offset": -0.03,
            "slope": 0.987
          },
          "performer": "Can Tho soil laboratory",
          "accreditation": "iso17025_lab",
          "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
          "valid_until": 1805552000.0,
          "supersedes": null,
          "created_at": 1790001000.0,
          "created_by": "admin@coop.example",
          "superseded_by": null
        }
      },
      "Calibrations": {
        "type": "object",
        "description": "SENS-B1d (#234): a device's calibrations, newest first (by `calibrated_at`, then id), at most 1000.",
        "additionalProperties": false,
        "required": [
          "device_id",
          "items"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Calibration"
            }
          }
        },
        "example": {
          "device_id": "soil-07",
          "items": [
            {
              "id": 12,
              "device_id": "soil-07",
              "sensor_serial": "RS485-4IN1-00172",
              "capability": "soil.ph",
              "calibrated_at": 1790000000.0,
              "method": "ph_buffers",
              "reference_values": {
                "buffers_ph": [
                  4.01,
                  7.0,
                  10.01
                ]
              },
              "coefficients": {
                "offset": -0.03,
                "slope": 0.987
              },
              "performer": "Can Tho soil laboratory",
              "accreditation": "iso17025_lab",
              "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
              "valid_until": 1805552000.0,
              "supersedes": null,
              "created_at": 1790001000.0,
              "created_by": "admin@coop.example",
              "superseded_by": null
            }
          ]
        }
      },
      "DeviceMetadata": {
        "type": "object",
        "description": "SENS-B1d (#234): what a device's readings can be judged by: the placement version in force (#225) and the calibrations not superseded. This is the document an EPCIS `deviceMetadata` link of the device's readings can name: `https://txng.theio.vn/v1/devices/{id}/metadata` (on this deployment's origin); readable only by the device's company and CropPath, never public. EPCIS exports do not link it yet.",
        "additionalProperties": false,
        "required": [
          "device_id",
          "placement",
          "calibrations",
          "as_of"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "placement": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/DevicePlacement"
              },
              {
                "type": "null"
              }
            ],
            "description": "The placement version in force at `as_of` (an installation, or a removal); null when none has started."
          },
          "calibrations": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Calibration"
            },
            "description": "The calibrations not superseded, newest first, at most 1000."
          },
          "as_of": {
            "type": "number",
            "description": "The server time the placement in force was read at."
          }
        },
        "example": {
          "device_id": "soil-07",
          "placement": {
            "device_id": "soil-07",
            "version": 2,
            "mobility": "fixed",
            "key_protection": "hardware",
            "gnss": false,
            "growing_area": "VN-TG-CL-0042",
            "lat": 10.3512345,
            "lon": 106.1234567,
            "accuracy_m": 3.5,
            "fix_at": 1790100000.0,
            "installed_at": 1790100600.0,
            "installer": "Nguyen Van A",
            "photo_sha256": "9b2f00000000000000000000000000000000000000000000000000000000a17c",
            "depth_cm": 30.0,
            "sensor_serial": "RS485-4IN1-00172",
            "note": "Moved to block B after replanting",
            "removed_at": null,
            "recorded_at": 1790101000.0,
            "valid_until": null
          },
          "calibrations": [
            {
              "id": 12,
              "device_id": "soil-07",
              "sensor_serial": "RS485-4IN1-00172",
              "capability": "soil.ph",
              "calibrated_at": 1790000000.0,
              "method": "ph_buffers",
              "reference_values": {
                "buffers_ph": [
                  4.01,
                  7.0,
                  10.01
                ]
              },
              "coefficients": {
                "offset": -0.03,
                "slope": 0.987
              },
              "performer": "Can Tho soil laboratory",
              "accreditation": "iso17025_lab",
              "certificate_sha256": "5d41402abc4b2a76b9719d911017c592ae2f1f9e2c1b0a7d9b8e3f4a6c2d1e0f",
              "valid_until": 1805552000.0,
              "supersedes": null,
              "created_at": 1790001000.0,
              "created_by": "admin@coop.example",
              "superseded_by": null
            }
          ],
          "as_of": 1790200000.0
        }
      },
      "SeqGap": {
        "type": "object",
        "required": [
          "device_id",
          "start_seq",
          "end_seq",
          "missing",
          "opened_at",
          "alerted"
        ],
        "additionalProperties": false,
        "description": "B9 (#21): an open range of sequence numbers a device has not sent yet (inclusive). It closes, and leaves the list, when the missing messages arrive.",
        "properties": {
          "device_id": {
            "type": "string"
          },
          "start_seq": {
            "type": "integer",
            "minimum": 0,
            "description": "First missing sequence number."
          },
          "end_seq": {
            "type": "integer",
            "minimum": 0,
            "description": "Last missing sequence number."
          },
          "missing": {
            "type": "integer",
            "minimum": 1,
            "description": "How many numbers are missing: end_seq - start_seq + 1."
          },
          "opened_at": {
            "type": "number",
            "description": "Unix seconds: when the server first saw the gap."
          },
          "alerted": {
            "type": "boolean",
            "description": "Whether the gap has been open long enough to raise a `seq_gap` alert."
          }
        },
        "example": {
          "device_id": "scale-1",
          "start_seq": 4,
          "end_seq": 6,
          "missing": 3,
          "opened_at": 1790000000.5,
          "alerted": true
        }
      },
      "SeqGapPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SeqGap"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last page."
          }
        }
      },
      "Rejection": {
        "type": "object",
        "required": [
          "id",
          "route",
          "envelope_id",
          "reason",
          "received_at",
          "payload_bytes"
        ],
        "additionalProperties": false,
        "description": "B9 (#21): a device message the server refused (not stored as a record). The payload itself is never returned: raw, untrusted device bytes.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "route": {
            "type": [
              "string",
              "null"
            ],
            "description": "The ingest route the message came on, `{tenant}/{site}/{device}/{kind}[/{eventType}]` as the sender wrote it (not proof of who sent it)."
          },
          "envelope_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The envelope id, when one could be read."
          },
          "reason": {
            "type": "string",
            "description": "Why it was refused, for example `bad_signature`, `malformed`."
          },
          "received_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "payload_bytes": {
            "type": "integer",
            "minimum": 0,
            "description": "Size of the stored payload (at most 65,536 bytes are kept)."
          }
        },
        "example": {
          "id": 41,
          "route": "coop-dl/ph1/scale-1/event/ObjectEvent",
          "envelope_id": "3f2b8f0e-6a39-4f7e-9b1e-0d6c1c5e7a11",
          "reason": "bad_signature",
          "received_at": 1790000000.5,
          "payload_bytes": 812
        }
      },
      "RejectionPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Rejection"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last page."
          }
        }
      },
      "OutboundTarget": {
        "type": "object",
        "required": [
          "target",
          "pending",
          "held",
          "failing",
          "next_attempt_at",
          "max_attempts",
          "last_error"
        ],
        "additionalProperties": false,
        "description": "B9 (#21): the company's undelivered events for one outbound target (a national system, a buyer's EPCIS repository, an archive).",
        "properties": {
          "target": {
            "type": "string",
            "description": "The target's name, as the deployment configures it."
          },
          "pending": {
            "type": "integer",
            "minimum": 0,
            "description": "Accepted events waiting to be delivered."
          },
          "held": {
            "type": "integer",
            "minimum": 0,
            "description": "Events not delivered because they are no longer accepted (for example sent back to quarantine by a pack), which wait until a review accepts them again."
          },
          "failing": {
            "type": "integer",
            "minimum": 0,
            "description": "Pending events whose delivery failed at least once."
          },
          "next_attempt_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds: the earliest next delivery attempt of a pending event; null when none is pending."
          },
          "max_attempts": {
            "type": "integer",
            "minimum": 0,
            "description": "The most failed attempts of one waiting event."
          },
          "last_error": {
            "type": [
              "string",
              "null"
            ],
            "description": "The error of the waiting event that failed most often (the latest next attempt among equals); null when none failed. One delivery batch carries several companies' events and a partner's error body can echo any of them, so a company sees only a tenant-neutral summary: `HTTP <status>` when the partner answered with an HTTP error, else `delivery_error`. A platform admin sees the full text (at most 500 characters)."
          }
        },
        "example": {
          "target": "epcis",
          "pending": 12,
          "held": 1,
          "failing": 12,
          "next_attempt_at": 1790000960.5,
          "max_attempts": 5,
          "last_error": "HTTP 503"
        }
      },
      "OutboundBacklog": {
        "type": "object",
        "required": [
          "targets"
        ],
        "additionalProperties": false,
        "properties": {
          "targets": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OutboundTarget"
            },
            "description": "Every configured target, and any other target with events waiting, by name."
          }
        }
      },
      "AlertResolution": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "note": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 500,
            "description": "Why the alert is resolved, at most 500 characters (after trimming). Kept in the audit row of the request, not on the alert."
          }
        },
        "example": {
          "note": "Scale replaced; the missing readings were re-entered by hand."
        }
      },
      "FacilityGln": {
        "type": "object",
        "required": [
          "facility",
          "gln"
        ],
        "additionalProperties": false,
        "description": "#161: a facility's GLN (EPCIS read point and business location of its events).",
        "properties": {
          "facility": {
            "type": "string"
          },
          "gln": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{13}$",
            "description": "GS1 Global Location Number: 13 digits, the last the GS1 mod-10 check digit; null when none."
          }
        },
        "example": {
          "facility": "VN-TGPH-021",
          "gln": "6141410000014"
        }
      },
      "GrowingAreaGln": {
        "type": "object",
        "required": [
          "growing_area",
          "gln"
        ],
        "additionalProperties": false,
        "description": "#161: a growing area's GLN (EPCIS read point of its events in staff documents; never in a public document).",
        "properties": {
          "growing_area": {
            "type": "string"
          },
          "gln": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{13}$",
            "description": "GS1 Global Location Number: 13 digits, the last the GS1 mod-10 check digit; null when none."
          }
        },
        "example": {
          "growing_area": "VN-TGOR-0387",
          "gln": "6141410000014"
        }
      },
      "GlnChange": {
        "description": "Set the GLN (13 digits with its check digit, a number of the company's own GS1 membership, not under the platform's prefix), clear it (null), or allocate the next GLN of the platform's GS1 company prefix (`allocate: true`).",
        "oneOf": [
          {
            "type": "object",
            "required": [
              "gln"
            ],
            "additionalProperties": false,
            "properties": {
              "gln": {
                "type": [
                  "string",
                  "null"
                ],
                "pattern": "^[0-9]{13}$"
              }
            }
          },
          {
            "type": "object",
            "required": [
              "allocate"
            ],
            "additionalProperties": false,
            "properties": {
              "allocate": {
                "const": true
              }
            }
          }
        ],
        "example": {
          "gln": "6141410000014"
        }
      },
      "ProductGtin": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "product",
          "variety",
          "grade",
          "gtin",
          "allocated",
          "created_by",
          "created_at"
        ],
        "description": "#161: the GTIN of one of the company's trade items (product, variety, grade; null: any variety, an ungraded item). A lot created without a GTIN takes the GTIN of its ungraded (product, variety).",
        "properties": {
          "product": {
            "type": "string"
          },
          "variety": {
            "type": [
              "string",
              "null"
            ]
          },
          "grade": {
            "type": [
              "string",
              "null"
            ]
          },
          "gtin": {
            "type": "string",
            "pattern": "^[0-9]{14}$",
            "description": "14 digits with the GS1 check digit."
          },
          "allocated": {
            "type": "boolean",
            "description": "Allocated from the platform's GS1 company prefix."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          }
        },
        "example": {
          "product": "durian",
          "variety": "Ri6",
          "grade": null,
          "gtin": "09520000000011",
          "allocated": true,
          "created_by": "admin@coop.example",
          "created_at": 1790000000.5
        }
      },
      "ProductGtinList": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 500,
            "items": {
              "$ref": "#/components/schemas/ProductGtin"
            }
          }
        },
        "example": {
          "items": [
            {
              "product": "durian",
              "variety": "Ri6",
              "grade": null,
              "gtin": "09520000000011",
              "allocated": true,
              "created_by": "admin@coop.example",
              "created_at": 1790000000.5
            }
          ]
        }
      },
      "ProductGtinCreate": {
        "type": "object",
        "required": [
          "product"
        ],
        "additionalProperties": false,
        "description": "Without `gtin`, the next GTIN of the platform's GS1 company prefix is allocated.",
        "properties": {
          "product": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64
          },
          "variety": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 64
          },
          "grade": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[A-Za-z0-9][A-Za-z0-9 ._-]{0,15}$"
          },
          "gtin": {
            "type": "string",
            "pattern": "^[0-9]{14}$",
            "description": "A GTIN of the company's own GS1 membership (14 digits, check digit)."
          }
        },
        "example": {
          "product": "durian",
          "variety": "Ri6"
        }
      },
      "PalletCarton": {
        "type": "object",
        "required": [
          "code",
          "lot",
          "epc"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string"
          },
          "lot": {
            "type": "string"
          },
          "epc": {
            "type": "string",
            "description": "The carton's EPC: its SGTIN Digital Link when its lot has a GTIN, else urn:agritrace:carton:<code>."
          }
        },
        "example": {
          "code": "C-014-0001",
          "lot": "LO-260928-014",
          "epc": "https://id.gs1.org/01/09520000000011/21/Xk3pQ9vT2mLr7Wb4Yz1A"
        }
      },
      "Pallet": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "sscc",
          "facility",
          "epc",
          "element_string",
          "cartons",
          "created_by",
          "created_at",
          "updated_at"
        ],
        "description": "#161: a pallet of a facility, identified by its SSCC, with the cartons on it.",
        "properties": {
          "sscc": {
            "type": "string",
            "pattern": "^[0-9]{18}$",
            "description": "GS1 Serial Shipping Container Code: 18 digits, the last the GS1 mod-10 check digit."
          },
          "facility": {
            "type": "string"
          },
          "epc": {
            "type": "string",
            "description": "https://id.gs1.org/00/<sscc>"
          },
          "element_string": {
            "type": "string",
            "description": "GS1-128 element string, (00)<sscc>."
          },
          "cartons": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/PalletCarton"
            }
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          }
        },
        "example": {
          "sscc": "095200000000000011",
          "facility": "VN-TGPH-021",
          "epc": "https://id.gs1.org/00/095200000000000011",
          "element_string": "(00)095200000000000011",
          "cartons": [
            {
              "code": "C-014-0001",
              "lot": "LO-260928-014",
              "epc": "https://id.gs1.org/01/09520000000011/21/Xk3pQ9vT2mLr7Wb4Yz1A"
            }
          ],
          "created_by": "packer@coop.example",
          "created_at": 1790000000.5,
          "updated_at": 1790000060.5
        }
      },
      "PalletSummary": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "sscc",
          "facility",
          "epc",
          "element_string",
          "carton_count",
          "created_by",
          "created_at",
          "updated_at"
        ],
        "properties": {
          "sscc": {
            "type": "string",
            "pattern": "^[0-9]{18}$",
            "description": "GS1 Serial Shipping Container Code: 18 digits, the last the GS1 mod-10 check digit."
          },
          "facility": {
            "type": "string"
          },
          "epc": {
            "type": "string"
          },
          "element_string": {
            "type": "string"
          },
          "carton_count": {
            "type": "integer",
            "minimum": 0
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "updated_at": {
            "type": "number"
          }
        },
        "example": {
          "sscc": "095200000000000011",
          "facility": "VN-TGPH-021",
          "epc": "https://id.gs1.org/00/095200000000000011",
          "element_string": "(00)095200000000000011",
          "carton_count": 40,
          "created_by": "packer@coop.example",
          "created_at": 1790000000.5,
          "updated_at": 1790000060.5
        }
      },
      "PalletPage": {
        "type": "object",
        "required": [
          "items",
          "next_cursor"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PalletSummary"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "items": [
            {
              "sscc": "095200000000000011",
              "facility": "VN-TGPH-021",
              "epc": "https://id.gs1.org/00/095200000000000011",
              "element_string": "(00)095200000000000011",
              "carton_count": 40,
              "created_by": "packer@coop.example",
              "created_at": 1790000000.5,
              "updated_at": 1790000060.5
            }
          ],
          "next_cursor": null
        }
      },
      "PalletCreate": {
        "type": "object",
        "required": [
          "facility"
        ],
        "additionalProperties": false,
        "description": "Without `sscc`, the next SSCC of the platform's GS1 company prefix is allocated.",
        "properties": {
          "facility": {
            "type": "string"
          },
          "sscc": {
            "type": "string",
            "pattern": "^[0-9]{18}$",
            "description": "An SSCC of the company's own GS1 membership."
          }
        },
        "example": {
          "facility": "VN-TGPH-021"
        }
      },
      "PalletCartons": {
        "type": "object",
        "required": [
          "cartons"
        ],
        "additionalProperties": false,
        "properties": {
          "cartons": {
            "type": "array",
            "maxItems": 200,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^C-[0-9]{3,19}-[0-9]{4}$"
            }
          },
          "expected_cartons": {
            "type": "array",
            "maxItems": 200,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^C-[0-9]{3,19}-[0-9]{4}$"
            },
            "description": "The precondition (#267): the codes of every carton the writer read on the pallet (Pallet.cartons, all lots, any order). When given, the set is refused with 409 `pallet_changed` if the pallet now holds other cartons, so a change made since that read is never overwritten. Without it the set replaces what the pallet holds."
          }
        },
        "example": {
          "cartons": [
            "C-014-0001",
            "C-014-0002"
          ],
          "expected_cartons": [
            "C-014-0001"
          ]
        }
      },
      "ShipmentSscc": {
        "type": "object",
        "required": [
          "shipment",
          "sscc",
          "epc",
          "element_string"
        ],
        "additionalProperties": false,
        "description": "#161: the SSCC of a shipment's container load; null until set.",
        "properties": {
          "shipment": {
            "type": "string"
          },
          "sscc": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9]{18}$",
            "description": "GS1 Serial Shipping Container Code: 18 digits, the last the GS1 mod-10 check digit."
          },
          "epc": {
            "type": [
              "string",
              "null"
            ]
          },
          "element_string": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "shipment": "SH-2026-0042",
          "sscc": "095200000000000011",
          "epc": "https://id.gs1.org/00/095200000000000011",
          "element_string": "(00)095200000000000011"
        }
      },
      "SsccChange": {
        "description": "Set the SSCC (a number of the company's own GS1 membership, not under the platform's prefix), or allocate the next SSCC of the platform's GS1 company prefix.",
        "oneOf": [
          {
            "type": "object",
            "required": [
              "sscc"
            ],
            "additionalProperties": false,
            "properties": {
              "sscc": {
                "type": "string",
                "pattern": "^[0-9]{18}$"
              }
            }
          },
          {
            "type": "object",
            "required": [
              "allocate"
            ],
            "additionalProperties": false,
            "properties": {
              "allocate": {
                "const": true
              }
            }
          }
        ],
        "example": {
          "allocate": true
        }
      },
      "LotGs1Carton": {
        "type": "object",
        "required": [
          "code",
          "carton_no",
          "epc",
          "element_string",
          "digital_link"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string"
          },
          "carton_no": {
            "type": "integer",
            "minimum": 1
          },
          "epc": {
            "type": "string"
          },
          "element_string": {
            "type": [
              "string",
              "null"
            ],
            "description": "(01)<gtin>(10)<lot>(21)<serial>; null without a GTIN."
          },
          "digital_link": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "code": "C-014-0001",
          "carton_no": 1,
          "epc": "https://id.gs1.org/01/09520000000011/21/Xk3pQ9vT2mLr7Wb4Yz1A",
          "element_string": "(01)09520000000011(10)LO-260928-014(21)Xk3pQ9vT2mLr7Wb4Yz1A",
          "digital_link": "https://txng.theio.vn/01/09520000000011/10/LO-260928-014/21/Xk3pQ9vT2mLr7Wb4Yz1A"
        }
      },
      "LotGs1Pallet": {
        "type": "object",
        "required": [
          "sscc",
          "element_string",
          "lot_cartons",
          "first_carton",
          "last_carton",
          "cartons"
        ],
        "additionalProperties": false,
        "properties": {
          "sscc": {
            "type": "string",
            "pattern": "^[0-9]{18}$",
            "description": "GS1 Serial Shipping Container Code: 18 digits, the last the GS1 mod-10 check digit."
          },
          "element_string": {
            "type": "string"
          },
          "lot_cartons": {
            "type": "integer",
            "minimum": 1
          },
          "first_carton": {
            "type": "integer",
            "minimum": 1,
            "description": "The lowest number of the lot's cartons on the pallet."
          },
          "last_carton": {
            "type": "integer",
            "minimum": 1,
            "description": "The highest number of the lot's cartons on the pallet."
          },
          "cartons": {
            "type": "integer",
            "minimum": 1,
            "description": "Every carton on the pallet, of any lot. The export pallet label prints the pallet's (00) when the pallet holds exactly the cartons the label is printed for."
          }
        },
        "example": {
          "sscc": "095200000000000011",
          "element_string": "(00)095200000000000011",
          "lot_cartons": 40,
          "first_carton": 1,
          "last_carton": 40,
          "cartons": 40
        }
      },
      "LotGs1Labels": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "gtin",
          "sealed",
          "element_string",
          "digital_link",
          "cartons",
          "pallets",
          "next_cursor"
        ],
        "description": "#161: what the lot's GS1 labels print. The lot-level element string and Digital Link exist when the lot has a GTIN and its code fits AI 10 (20 characters); the public resolver answers the Digital Link once the lot is sealed (`sealed`).",
        "properties": {
          "lot": {
            "type": "string"
          },
          "gtin": {
            "type": [
              "string",
              "null"
            ]
          },
          "sealed": {
            "type": "boolean"
          },
          "element_string": {
            "type": [
              "string",
              "null"
            ],
            "description": "(01)<gtin>(10)<lot>"
          },
          "digital_link": {
            "type": [
              "string",
              "null"
            ],
            "description": "<resolver base>/01/<gtin>/10/<lot>"
          },
          "cartons": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LotGs1Carton"
            }
          },
          "pallets": {
            "type": "array",
            "maxItems": 500,
            "items": {
              "$ref": "#/components/schemas/LotGs1Pallet"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "gtin": "09520000000011",
          "sealed": true,
          "element_string": "(01)09520000000011(10)LO-260928-014",
          "digital_link": "https://txng.theio.vn/01/09520000000011/10/LO-260928-014",
          "cartons": [
            {
              "code": "C-014-0001",
              "carton_no": 1,
              "epc": "https://id.gs1.org/01/09520000000011/21/Xk3pQ9vT2mLr7Wb4Yz1A",
              "element_string": "(01)09520000000011(10)LO-260928-014(21)Xk3pQ9vT2mLr7Wb4Yz1A",
              "digital_link": "https://txng.theio.vn/01/09520000000011/10/LO-260928-014/21/Xk3pQ9vT2mLr7Wb4Yz1A"
            }
          ],
          "pallets": [
            {
              "sscc": "095200000000000011",
              "element_string": "(00)095200000000000011",
              "lot_cartons": 40,
              "first_carton": 1,
              "last_carton": 40,
              "cartons": 40
            }
          ],
          "next_cursor": null
        }
      },
      "UiTelemetryBeacon": {
        "type": "object",
        "description": "A browser beacon (#81): a page kind, the page's Core Web Vitals in the browser's units and the uncaught errors it saw. At least one measure or error. No URL, id, message or stack.",
        "additionalProperties": false,
        "required": [
          "page"
        ],
        "properties": {
          "page": {
            "type": "string",
            "enum": [
              "landing",
              "lot",
              "fruit",
              "fruit_results",
              "privacy",
              "accessibility",
              "staff",
              "other"
            ],
            "description": "The kind of page, never its URL."
          },
          "lcp_ms": {
            "type": "number",
            "minimum": 0,
            "maximum": 120000,
            "description": "Largest Contentful Paint, milliseconds."
          },
          "cls": {
            "type": "number",
            "minimum": 0,
            "maximum": 100,
            "description": "Cumulative Layout Shift (largest session window)."
          },
          "inp_ms": {
            "type": "number",
            "minimum": 0,
            "maximum": 120000,
            "description": "Interaction to Next Paint, milliseconds."
          },
          "errors": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "kind"
              ],
              "properties": {
                "kind": {
                  "type": "string",
                  "enum": [
                    "error",
                    "rejection"
                  ],
                  "description": "An uncaught error, or an unhandled promise rejection."
                },
                "name": {
                  "type": "string",
                  "maxLength": 64,
                  "description": "The error's constructor name (`TypeError`); names outside the standard ones are counted as `other`. Default `Error`."
                }
              }
            }
          }
        }
      },
      "LotMergeInput": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "quantity_kg"
        ],
        "description": "One lot the merge consumes, with the kilograms taken from it.",
        "properties": {
          "lot": {
            "type": "string",
            "pattern": "^[A-Z0-9][A-Z0-9-]{2,39}$",
            "description": "Code of a lot of the caller's tenant (closed, packed or shipped, never merged before, not on hold, of the output lot's product)."
          },
          "quantity_kg": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1000000,
            "description": "Kilograms taken from this lot; for a packed lot at most its packed net mass plus the mass tolerance."
          }
        }
      },
      "LotMergeRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "inputs",
          "output_kg"
        ],
        "description": "A lot merge (#91): the input lots and the kilograms the output lot (the path's lot) holds.",
        "properties": {
          "inputs": {
            "type": "array",
            "minItems": 2,
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/LotMergeInput"
            },
            "description": "2 to 50 distinct lots, never the output lot itself."
          },
          "output_kg": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1000000,
            "description": "Kilograms of the output lot. Mass balance: it differs from the sum of the inputs' quantity_kg by at most mass_tolerance (5 %) of that sum."
          }
        }
      },
      "LotTransformation": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "event_id",
          "lot",
          "facility",
          "inputs",
          "input_kg",
          "output_kg",
          "mass_tolerance",
          "recorded_at"
        ],
        "description": "A lot merge (#91; the `transform` event type, FSMA 204 transformation CTE). Its EPCIS 2.0 TransformationEvent is in the staff EPCIS document of each of its lots.",
        "properties": {
          "event_id": {
            "type": "string",
            "format": "uuid",
            "description": "The merge's id: the eventID of its TransformationEvent is urn:uuid:<event_id>, and the records export rows of the merge carry it."
          },
          "lot": {
            "type": "string",
            "description": "The output lot's code."
          },
          "facility": {
            "type": "string",
            "description": "The facility the merge happened at: the output lot's."
          },
          "inputs": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LotMergeInput"
            },
            "description": "The lots the merge consumed, by code."
          },
          "input_kg": {
            "type": "number",
            "description": "The sum of the inputs' quantity_kg."
          },
          "output_kg": {
            "type": "number",
            "description": "The output lot's kilograms."
          },
          "mass_tolerance": {
            "type": "number",
            "description": "The share of input_kg by which output_kg may differ (0.05)."
          },
          "recorded_at": {
            "type": "number",
            "description": "When the merge was recorded (Unix seconds)."
          }
        }
      },
      "LotTransformations": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "produced_by",
          "consumed_by"
        ],
        "description": "The lot merges a lot took part in (#91).",
        "properties": {
          "produced_by": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/LotTransformation"
              },
              {
                "type": "null"
              }
            ],
            "description": "The merge that produced the lot; null when no merge did."
          },
          "consumed_by": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/LotTransformation"
              },
              {
                "type": "null"
              }
            ],
            "description": "The merge that consumed the lot; null when no merge did."
          }
        }
      },
      "Passkey": {
        "type": "object",
        "description": "#87. One of the signed-in user's passkeys: never its credential id, public key or user handle.",
        "required": [
          "id",
          "nickname",
          "algorithm",
          "transports",
          "attestation_format",
          "created_at",
          "last_used_at",
          "clone_warning_at"
        ],
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "integer",
            "minimum": 1
          },
          "nickname": {
            "type": "string",
            "maxLength": 64,
            "description": "The owner's name for it; empty when none was given."
          },
          "algorithm": {
            "type": "string",
            "enum": [
              "ES256",
              "RS256",
              "EdDSA"
            ]
          },
          "transports": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "ble",
                "hybrid",
                "internal",
                "nfc",
                "smart-card",
                "usb"
              ]
            },
            "description": "How the browser said the authenticator connects (hints)."
          },
          "attestation_format": {
            "type": "string",
            "maxLength": 32
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "last_used_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "Unix seconds of the last sign-in with it."
          },
          "clone_warning_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When a sign-in with it was refused because its signature counter did not move forward: the authenticator may have been copied. Remove the passkey if you did not expect this."
          }
        },
        "example": {
          "id": 3,
          "nickname": "Work phone",
          "algorithm": "ES256",
          "transports": [
            "hybrid",
            "internal"
          ],
          "attestation_format": "none",
          "created_at": 1790060400,
          "last_used_at": 1790086380,
          "clone_warning_at": null
        }
      },
      "PasskeyList": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 10,
            "items": {
              "$ref": "#/components/schemas/Passkey"
            }
          }
        }
      },
      "PasskeyRegistration": {
        "type": "object",
        "description": "#87. The answer of navigator.credentials.create(): `response.clientDataJSON` and `response.attestationObject`, base64url (padding optional), and `response.getTransports()`.",
        "required": [
          "client_data_json",
          "attestation_object"
        ],
        "additionalProperties": false,
        "properties": {
          "client_data_json": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+={0,2}$",
            "maxLength": 5464
          },
          "attestation_object": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+={0,2}$",
            "maxLength": 21848
          },
          "transports": {
            "type": "array",
            "maxItems": 16,
            "items": {
              "type": "string"
            },
            "description": "Unknown names are dropped."
          },
          "nickname": {
            "type": "string",
            "maxLength": 64
          }
        }
      },
      "PasskeyRename": {
        "type": "object",
        "required": [
          "nickname"
        ],
        "additionalProperties": false,
        "properties": {
          "nickname": {
            "type": "string",
            "maxLength": 64
          }
        }
      },
      "PasskeyCreationOptions": {
        "type": "object",
        "description": "#87. `public_key`: PublicKeyCredentialCreationOptions for navigator.credentials.create(), binary values as base64url (`challenge`, `user.id`, `excludeCredentials[].id`).",
        "required": [
          "public_key"
        ],
        "additionalProperties": false,
        "properties": {
          "public_key": {
            "type": "object",
            "required": [
              "challenge",
              "rp",
              "user",
              "pubKeyCredParams",
              "timeout",
              "attestation",
              "authenticatorSelection",
              "excludeCredentials"
            ],
            "additionalProperties": false,
            "properties": {
              "challenge": {
                "type": "string",
                "pattern": "^[A-Za-z0-9_-]+={0,2}$"
              },
              "rp": {
                "type": "object",
                "required": [
                  "id",
                  "name"
                ],
                "additionalProperties": false,
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              },
              "user": {
                "type": "object",
                "required": [
                  "id",
                  "name",
                  "displayName"
                ],
                "additionalProperties": false,
                "properties": {
                  "id": {
                    "type": "string",
                    "pattern": "^[A-Za-z0-9_-]+={0,2}$"
                  },
                  "name": {
                    "type": "string"
                  },
                  "displayName": {
                    "type": "string"
                  }
                }
              },
              "pubKeyCredParams": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "type",
                    "alg"
                  ],
                  "additionalProperties": false,
                  "properties": {
                    "type": {
                      "type": "string",
                      "const": "public-key"
                    },
                    "alg": {
                      "type": "integer"
                    }
                  }
                }
              },
              "timeout": {
                "type": "integer",
                "description": "Milliseconds."
              },
              "attestation": {
                "type": "string",
                "const": "none"
              },
              "authenticatorSelection": {
                "type": "object",
                "required": [
                  "residentKey",
                  "requireResidentKey",
                  "userVerification"
                ],
                "additionalProperties": false,
                "properties": {
                  "residentKey": {
                    "type": "string",
                    "const": "required"
                  },
                  "requireResidentKey": {
                    "type": "boolean",
                    "const": true
                  },
                  "userVerification": {
                    "type": "string",
                    "const": "required"
                  }
                }
              },
              "excludeCredentials": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "type",
                    "id"
                  ],
                  "additionalProperties": false,
                  "properties": {
                    "type": {
                      "type": "string",
                      "const": "public-key"
                    },
                    "id": {
                      "type": "string",
                      "pattern": "^[A-Za-z0-9_-]+={0,2}$"
                    },
                    "transports": {
                      "type": "array",
                      "items": {
                        "type": "string",
                        "enum": [
                          "ble",
                          "hybrid",
                          "internal",
                          "nfc",
                          "smart-card",
                          "usb"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "PasskeyRequestOptions": {
        "type": "object",
        "description": "#87. `public_key`: PublicKeyCredentialRequestOptions for navigator.credentials.get(), the challenge as base64url; no allowed credentials (the authenticator offers the person's passkeys for this site).",
        "required": [
          "public_key"
        ],
        "additionalProperties": false,
        "properties": {
          "public_key": {
            "type": "object",
            "required": [
              "challenge",
              "rpId",
              "timeout",
              "userVerification",
              "allowCredentials"
            ],
            "additionalProperties": false,
            "properties": {
              "challenge": {
                "type": "string",
                "pattern": "^[A-Za-z0-9_-]+={0,2}$"
              },
              "rpId": {
                "type": "string"
              },
              "timeout": {
                "type": "integer",
                "description": "Milliseconds."
              },
              "userVerification": {
                "type": "string",
                "const": "required"
              },
              "allowCredentials": {
                "type": "array",
                "maxItems": 0,
                "items": {
                  "type": "object"
                }
              }
            }
          }
        }
      },
      "PasskeyLogin": {
        "type": "object",
        "description": "#87. The answer of navigator.credentials.get(): the credential's `rawId`, `response.clientDataJSON`, `response.authenticatorData`, `response.signature` and `response.userHandle`, each base64url (padding optional).",
        "required": [
          "credential_id",
          "client_data_json",
          "authenticator_data",
          "signature",
          "user_handle"
        ],
        "additionalProperties": false,
        "properties": {
          "credential_id": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+={0,2}$",
            "maxLength": 1366
          },
          "client_data_json": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+={0,2}$",
            "maxLength": 5464
          },
          "authenticator_data": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+={0,2}$",
            "maxLength": 5464
          },
          "signature": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+={0,2}$",
            "maxLength": 1368
          },
          "user_handle": {
            "type": "string",
            "pattern": "^[A-Za-z0-9_-]+={0,2}$",
            "maxLength": 88
          }
        }
      },
      "FourEyesState": {
        "type": "object",
        "additionalProperties": false,
        "description": "INTEGRITY-3 (#203). The selected company's second admin approval: whether its critical actions wait for a second admin, how many active company admins it has (fewer than 2: CropPath support is the second approver), how many requests wait for a decision, and how long a request may wait.",
        "required": [
          "require_second_admin",
          "admins",
          "pending",
          "expires_after_s"
        ],
        "properties": {
          "require_second_admin": {
            "type": "boolean"
          },
          "admins": {
            "type": "integer",
            "minimum": 0,
            "description": "Active company admins (active membership and account)."
          },
          "pending": {
            "type": "integer",
            "minimum": 0,
            "description": "Requests waiting for a decision (not expired)."
          },
          "expires_after_s": {
            "type": "integer",
            "minimum": 1,
            "description": "Seconds a request may wait (72 hours)."
          }
        },
        "example": {
          "require_second_admin": true,
          "admins": 2,
          "pending": 1,
          "expires_after_s": 259200
        }
      },
      "FourEyesUpdate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "require_second_admin"
        ],
        "properties": {
          "require_second_admin": {
            "type": "boolean"
          }
        },
        "example": {
          "require_second_admin": true
        }
      },
      "ApprovalRequest": {
        "type": "object",
        "additionalProperties": false,
        "description": "INTEGRITY-3 (#203). A critical action one admin asked for, waiting for (or decided by) another admin of the company. `body` is the action's JSON body (public keys, grading rules or a yes/no: never a secret). `status` `expired`: it was not decided within 72 hours and can no longer be.",
        "required": [
          "id",
          "action",
          "method",
          "path",
          "body",
          "status",
          "requested_by",
          "requested_by_user_id",
          "requested_at",
          "expires_at",
          "decided_by",
          "decided_as",
          "decided_at",
          "reason"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "action": {
            "type": "string",
            "description": "The action's audit action, e.g. `key.create`, `grading_rule.update`."
          },
          "method": {
            "type": "string",
            "enum": [
              "POST",
              "PUT"
            ]
          },
          "path": {
            "type": "string",
            "description": "The path the action calls."
          },
          "body": {
            "type": "object",
            "description": "The action's JSON body."
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "approved",
              "rejected",
              "expired"
            ]
          },
          "requested_by": {
            "type": "string",
            "description": "Who asked (their sign-in email)."
          },
          "requested_by_user_id": {
            "type": "integer"
          },
          "requested_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "expires_at": {
            "type": "number",
            "description": "Unix seconds: a pending request can be decided until then."
          },
          "decided_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "decided_as": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "company_admin",
              "platform_support",
              null
            ],
            "description": "`platform_support`: CropPath support decided, acting for the company."
          },
          "decided_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "A rejection's reason."
          }
        },
        "example": {
          "id": 17,
          "action": "key.create",
          "method": "POST",
          "path": "/v1/keys",
          "body": {
            "kid": "gw-01-k2",
            "owner_type": "gateway",
            "owner_id": "gw-01",
            "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
          },
          "status": "pending",
          "requested_by": "admin@coop.example",
          "requested_by_user_id": 12,
          "requested_at": 1797000000.5,
          "expires_at": 1797259200.5,
          "decided_by": null,
          "decided_as": null,
          "decided_at": null,
          "reason": null
        }
      },
      "ApprovalRequestCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "method",
          "path"
        ],
        "properties": {
          "method": {
            "type": "string",
            "enum": [
              "POST",
              "PUT"
            ]
          },
          "path": {
            "type": "string",
            "maxLength": 512,
            "description": "The critical action's path, without a query."
          },
          "body": {
            "type": "object",
            "description": "The action's JSON body (default `{}`)."
          }
        },
        "example": {
          "method": "POST",
          "path": "/v1/keys",
          "body": {
            "kid": "gw-01-k2",
            "owner_type": "gateway",
            "owner_id": "gw-01",
            "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
          }
        }
      },
      "ApprovalRequestPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/ApprovalRequest"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 17,
              "action": "key.create",
              "method": "POST",
              "path": "/v1/keys",
              "body": {
                "kid": "gw-01-k2",
                "owner_type": "gateway",
                "owner_id": "gw-01",
                "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
              },
              "status": "pending",
              "requested_by": "admin@coop.example",
              "requested_by_user_id": 12,
              "requested_at": 1797000000.5,
              "expires_at": 1797259200.5,
              "decided_by": null,
              "decided_as": null,
              "decided_at": null,
              "reason": null
            }
          ],
          "next_cursor": null
        }
      },
      "ApprovalRequestApproved": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "request",
          "result"
        ],
        "properties": {
          "request": {
            "$ref": "#/components/schemas/ApprovalRequest"
          },
          "result": {
            "type": "object",
            "description": "The action's own answer, as if it had been called directly."
          }
        },
        "example": {
          "request": {
            "id": 17,
            "action": "key.create",
            "method": "POST",
            "path": "/v1/keys",
            "body": {
              "kid": "gw-01-k2",
              "owner_type": "gateway",
              "owner_id": "gw-01",
              "public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n"
            },
            "status": "approved",
            "requested_by": "admin@coop.example",
            "requested_by_user_id": 12,
            "requested_at": 1797000000.5,
            "expires_at": 1797259200.5,
            "decided_by": "second@coop.example",
            "decided_as": "company_admin",
            "decided_at": 1797003600.5,
            "reason": null
          },
          "result": {
            "kid": "gw-01-k2",
            "owner_type": "gateway"
          }
        }
      },
      "ApprovalRequestRejection": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500
          }
        },
        "example": {
          "reason": "Not our gateway."
        }
      },
      "GrowerConsent": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "channel",
          "consent_date",
          "decision",
          "evidence_sha256",
          "grower_id",
          "id",
          "market",
          "purpose",
          "recorded_at",
          "recorded_by",
          "request_id",
          "scope"
        ],
        "description": "#163. One decision of a grower about one purpose and market (append-only); the latest of a (purpose, market) is the one in force.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "grower_id": {
            "type": "integer"
          },
          "purpose": {
            "type": "string",
            "enum": [
              "public_name",
              "orchard_position"
            ],
            "description": "`public_name`: the grower's name on the public fruit page; `orchard_position`: the orchard's position on public pages (no public page shows one today)."
          },
          "market": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[A-Z]{2}$",
            "description": "ISO 3166-1 alpha-2 market the decision is for; null: every market."
          },
          "decision": {
            "type": "string",
            "enum": [
              "granted",
              "withdrawn"
            ]
          },
          "channel": {
            "type": "string",
            "enum": [
              "paper",
              "electronic",
              "in_person",
              "record_edit",
              "migrated",
              "data_request"
            ],
            "description": "How the decision reached the company: a signed `paper` form, an `electronic` message, `in_person` or by phone; or, written by the platform, `record_edit` (the grower form's consent flag), `migrated` (a consent recorded before #163), `data_request` (withdrawn while handling the grower's request `request_id`)."
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the evidence (the scanned form or the message), or null."
          },
          "consent_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The day on the form (YYYY-MM-DD), or null."
          },
          "scope": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "What the decision covers (staff-only text), or null."
          },
          "request_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The grower data request handled with this withdrawal (`data_request`), or null."
          },
          "recorded_at": {
            "type": "number",
            "description": "Seconds since 1970 (UTC)."
          },
          "recorded_by": {
            "type": "string",
            "description": "Who recorded it: an opaque operator id (`user-<id>`, `token-<id>`, `client-<id>`), never an email; `system` or `migration` for the platform."
          }
        },
        "example": {
          "id": 31,
          "grower_id": 12,
          "purpose": "public_name",
          "market": null,
          "decision": "granted",
          "channel": "paper",
          "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
          "consent_date": "2026-09-12",
          "scope": "Fruit pages, every market",
          "request_id": null,
          "recorded_at": 1790000000.5,
          "recorded_by": "user-7"
        }
      },
      "GrowerConsentCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "purpose",
          "decision",
          "channel"
        ],
        "description": "#163. A grower's decision as staff record it. A grant needs written evidence: `channel` `paper` or `electronic` and `evidence_sha256`; a withdrawal is accepted however the grower made it.",
        "properties": {
          "purpose": {
            "type": "string",
            "enum": [
              "public_name",
              "orchard_position"
            ],
            "description": "`public_name`: the grower's name on the public fruit page; `orchard_position`: the orchard's position on public pages (no public page shows one today)."
          },
          "market": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[A-Z]{2}$",
            "description": "ISO 3166-1 alpha-2 market the decision is for; null: every market."
          },
          "decision": {
            "type": "string",
            "enum": [
              "granted",
              "withdrawn"
            ]
          },
          "channel": {
            "type": "string",
            "enum": [
              "paper",
              "electronic",
              "in_person"
            ]
          },
          "evidence_sha256": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[0-9a-f]{64}$",
            "description": "SHA-256 of the evidence (64 lowercase hex digits); required for a grant."
          },
          "consent_date": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The day on the form (YYYY-MM-DD), from 2000-01-01, not after today."
          },
          "scope": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "What it covers: one line of at most 200 characters (staff-only)."
          }
        },
        "example": {
          "purpose": "public_name",
          "market": null,
          "decision": "granted",
          "channel": "paper",
          "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
          "consent_date": "2026-09-12",
          "scope": "Fruit pages, every market"
        }
      },
      "GrowerConsentPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "grower_id",
          "in_force",
          "items",
          "next_cursor"
        ],
        "description": "#163. A grower's consents in force and one page of its consent records, newest first.",
        "properties": {
          "grower_id": {
            "type": "integer"
          },
          "in_force": {
            "type": "array",
            "maxItems": 512,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "purpose",
                "market",
                "evidence_recorded"
              ],
              "properties": {
                "purpose": {
                  "type": "string",
                  "enum": [
                    "public_name",
                    "orchard_position"
                  ],
                  "description": "`public_name`: the grower's name on the public fruit page; `orchard_position`: the orchard's position on public pages (no public page shows one today)."
                },
                "market": {
                  "type": [
                    "string",
                    "null"
                  ],
                  "pattern": "^[A-Z]{2}$",
                  "description": "ISO 3166-1 alpha-2 market the decision is for; null: every market."
                },
                "evidence_recorded": {
                  "type": "boolean",
                  "description": "Whether the grant in force carries the SHA-256 of its evidence. False for a grant made through the grower's `public_consent` flag (createGrower, updateGrower, the grower batch: channel `record_edit`, kept for SDK 0.2.0 and to be deprecated) or recorded before the consent records existed (`migrated`): staff are shown \"no evidence recorded\"."
                }
              }
            },
            "description": "Every (purpose, market) whose latest decision is a grant. The public fruit page names the grower with `public_name` for the destination market of the shipment its lot is on, or else with `public_name` for every market (`market` null); a lot on no shipment has no market, so only the every-market consent names the grower there."
          },
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/GrowerConsent"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "grower_id": 12,
          "in_force": [],
          "items": [
            {
              "id": 32,
              "grower_id": 12,
              "purpose": "public_name",
              "market": null,
              "decision": "withdrawn",
              "channel": "in_person",
              "evidence_sha256": null,
              "consent_date": null,
              "scope": null,
              "request_id": null,
              "recorded_at": 1790086400.5,
              "recorded_by": "user-7"
            },
            {
              "id": 31,
              "grower_id": 12,
              "purpose": "public_name",
              "market": null,
              "decision": "granted",
              "channel": "paper",
              "evidence_sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
              "consent_date": "2026-09-12",
              "scope": "Fruit pages, every market",
              "request_id": null,
              "recorded_at": 1790000000.5,
              "recorded_by": "user-7"
            }
          ],
          "next_cursor": null
        }
      },
      "GrowerDataRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "answer",
          "channel",
          "created_at",
          "created_by",
          "due_on",
          "grower",
          "handled_at",
          "handled_by",
          "id",
          "kind",
          "overdue",
          "received_on",
          "status",
          "text",
          "withdrawn"
        ],
        "description": "#163. A grower's request about their personal data, as the company received it.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "grower": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "id",
              "name"
            ],
            "properties": {
              "id": {
                "type": "integer"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "kind": {
            "type": "string",
            "enum": [
              "access",
              "rectification",
              "erasure",
              "objection"
            ]
          },
          "channel": {
            "type": "string",
            "enum": [
              "paper",
              "electronic",
              "in_person"
            ]
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "The grower's request as received: plain text, never HTML or markdown."
          },
          "received_on": {
            "type": "string",
            "format": "date"
          },
          "due_on": {
            "type": "string",
            "format": "date",
            "description": "The day the answer is due: 30 days after `received_on` (a proposal pending counsel)."
          },
          "overdue": {
            "type": "boolean",
            "description": "Open and past `due_on` (UTC)."
          },
          "status": {
            "type": "string",
            "enum": [
              "open",
              "handled"
            ]
          },
          "created_at": {
            "type": "number",
            "description": "Seconds since 1970 (UTC)."
          },
          "created_by": {
            "type": "string",
            "description": "Who entered it: an opaque operator id, never an email."
          },
          "handled_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "handled_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "An opaque operator id, or null."
          },
          "answer": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 2000,
            "description": "The answer given to the grower (plain text), or null while open."
          },
          "withdrawn": {
            "type": [
              "array",
              "null"
            ],
            "maxItems": 512,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "purpose",
                "market"
              ],
              "properties": {
                "purpose": {
                  "type": "string",
                  "enum": [
                    "public_name",
                    "orchard_position"
                  ],
                  "description": "`public_name`: the grower's name on the public fruit page; `orchard_position`: the orchard's position on public pages (no public page shows one today)."
                },
                "market": {
                  "type": [
                    "string",
                    "null"
                  ],
                  "pattern": "^[A-Z]{2}$",
                  "description": "ISO 3166-1 alpha-2 market the decision is for; null: every market."
                }
              }
            },
            "description": "The consents withdrawn when the request was handled (empty: none), or null while open."
          }
        },
        "example": {
          "id": 4,
          "grower": {
            "id": 12,
            "name": "Nguyễn Văn An"
          },
          "kind": "erasure",
          "channel": "paper",
          "text": "Please take my name off the fruit pages.",
          "received_on": "2026-09-28",
          "due_on": "2026-10-28",
          "overdue": false,
          "status": "open",
          "created_at": 1790000000.5,
          "created_by": "user-7",
          "handled_at": null,
          "handled_by": null,
          "answer": null,
          "withdrawn": null
        }
      },
      "GrowerDataRequestCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "grower_id",
          "kind",
          "channel",
          "received_on",
          "text"
        ],
        "properties": {
          "grower_id": {
            "type": "integer",
            "minimum": 1
          },
          "kind": {
            "type": "string",
            "enum": [
              "access",
              "rectification",
              "erasure",
              "objection"
            ]
          },
          "channel": {
            "type": "string",
            "enum": [
              "paper",
              "electronic",
              "in_person"
            ]
          },
          "received_on": {
            "type": "string",
            "format": "date",
            "description": "The day the company received it (YYYY-MM-DD), from 2000-01-01, not after today."
          },
          "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "1 to 2000 characters after trimming; line breaks and tabs allowed, no other control characters. Stored and shown as plain text."
          }
        },
        "example": {
          "grower_id": 12,
          "kind": "erasure",
          "channel": "paper",
          "received_on": "2026-09-28",
          "text": "Please take my name off the fruit pages."
        }
      },
      "GrowerDataRequestHandle": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "answer"
        ],
        "properties": {
          "answer": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "The answer given to the grower, as plain text (1 to 2000 characters after trimming)."
          },
          "withdraw_public": {
            "type": "boolean",
            "default": false,
            "description": "Erasure or objection only: also withdraw every consent in force (each recorded as a `data_request` withdrawal); the name leaves the public fruit page at once."
          }
        },
        "example": {
          "answer": "Your name no longer shows on the public fruit pages. The signed lot records never named you; the company keeps your name in its own registry for traceability.",
          "withdraw_public": true
        }
      },
      "GrowerDataRequestPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor"
        ],
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/GrowerDataRequest"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last."
          }
        },
        "example": {
          "items": [
            {
              "id": 4,
              "grower": {
                "id": 12,
                "name": "Nguyễn Văn An"
              },
              "kind": "erasure",
              "channel": "paper",
              "text": "Please take my name off the fruit pages.",
              "received_on": "2026-09-28",
              "due_on": "2026-10-28",
              "overdue": false,
              "status": "handled",
              "created_at": 1790000000.5,
              "created_by": "user-7",
              "handled_at": 1790086400.5,
              "handled_by": "user-7",
              "answer": "Your name no longer shows on the public fruit pages. The signed lot records never named you; the company keeps your name in its own registry for traceability.",
              "withdrawn": [
                {
                  "purpose": "public_name",
                  "market": null
                }
              ]
            }
          ],
          "next_cursor": null
        }
      },
      "CropNames": {
        "type": "object",
        "required": [
          "vi",
          "en",
          "zh-Hans"
        ],
        "additionalProperties": false,
        "description": "The crop's name in Vietnamese, English and Simplified Chinese (each 1 to 100 characters).",
        "properties": {
          "vi": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100
          },
          "en": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100
          },
          "zh-Hans": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100
          }
        }
      },
      "Crop": {
        "type": "object",
        "required": [
          "code",
          "names",
          "ripeness_scale",
          "created_at",
          "updated_at"
        ],
        "additionalProperties": false,
        "description": "A crop of the platform's crop registry.",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$",
            "description": "The crop code that lots (`product`) and growing areas (`crop`) name."
          },
          "names": {
            "$ref": "#/components/schemas/CropNames"
          },
          "ripeness_scale": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "levels_1_to_4",
              null
            ],
            "description": "The crop's ripeness scale: `levels_1_to_4`, the four ripeness levels a durian is graded on (1 immature, 2 mature-firm, 3 just ripe, 4 overripe); null when the crop has no ripeness scale."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds (0 for the crop the platform started with)."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds of the last change."
          }
        }
      },
      "CropCreate": {
        "type": "object",
        "required": [
          "code",
          "names"
        ],
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$",
            "description": "The crop code that lots (`product`) and growing areas (`crop`) name."
          },
          "names": {
            "$ref": "#/components/schemas/CropNames"
          },
          "ripeness_scale": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "levels_1_to_4",
              null
            ],
            "description": "The crop's ripeness scale: `levels_1_to_4`, the four ripeness levels a durian is graded on (1 immature, 2 mature-firm, 3 just ripe, 4 overripe); null when the crop has no ripeness scale (never for `durian`, whose ripeness the knocker grades: a null scale for it is 400 `invalid_ripeness_scale`)."
          }
        }
      },
      "CropUpdate": {
        "type": "object",
        "minProperties": 1,
        "additionalProperties": false,
        "properties": {
          "names": {
            "$ref": "#/components/schemas/CropNames"
          },
          "ripeness_scale": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "levels_1_to_4",
              null
            ],
            "description": "The crop's ripeness scale: `levels_1_to_4`, the four ripeness levels a durian is graded on (1 immature, 2 mature-firm, 3 just ripe, 4 overripe); null when the crop has no ripeness scale (never for `durian`, whose ripeness the knocker grades: a null scale for it is 400 `invalid_ripeness_scale`)."
          }
        }
      },
      "CropList": {
        "type": "object",
        "required": [
          "items",
          "configured"
        ],
        "additionalProperties": false,
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Crop"
            },
            "description": "Every crop of the registry, by code (at most 200)."
          },
          "configured": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "The deployment's configured crops (the crops a published code list may name) that have no registry entry: lots and growing areas may name them too, without a sampling rule, a registration protocol or grading rules of their own."
          }
        }
      },
      "CropSampling": {
        "type": "object",
        "required": [
          "rule",
          "rule_source",
          "base_rate",
          "clean_rate",
          "clean_days",
          "analytes"
        ],
        "additionalProperties": false,
        "description": "A market's sampling rule for the crop: the share of a lot's export fruits sampled, the lower share once the growing area went `clean_days` without a failed sample, and the analytes a lab tests.",
        "properties": {
          "rule": {
            "type": "string",
            "pattern": "^[a-z0-9][a-z0-9._-]{0,63}$",
            "description": "The rule's id, unique across crops and markets; every sampling records it."
          },
          "rule_source": {
            "type": "string",
            "description": "The http(s) address of the published rule."
          },
          "base_rate": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1,
            "description": "0.02 is 2%."
          },
          "clean_rate": {
            "type": "number",
            "exclusiveMinimum": 0,
            "maximum": 1
          },
          "clean_days": {
            "type": "integer",
            "minimum": 1,
            "maximum": 3650
          },
          "analytes": {
            "type": "array",
            "minItems": 1,
            "maxItems": 16,
            "uniqueItems": true,
            "items": {
              "type": "string",
              "pattern": "^[a-z][a-z0-9_]{0,63}$"
            }
          },
          "analytes_source": {
            "type": [
              "string",
              "null"
            ],
            "description": "The http(s) address that requires these tests; optional."
          }
        }
      },
      "CropMarketRule": {
        "type": "object",
        "required": [
          "crop",
          "market",
          "registration_protocol",
          "sampling",
          "created_at",
          "updated_at"
        ],
        "additionalProperties": false,
        "description": "A crop's rules for one destination market.",
        "properties": {
          "crop": {
            "type": "string"
          },
          "market": {
            "type": "string",
            "description": "ISO 3166-1 alpha-2."
          },
          "registration_protocol": {
            "type": "boolean",
            "description": "Whether the market's registration protocol applies to the crop: the public lot page then names the protocol for a lot of the crop whose growing area grows it and has a GACC growing-area code."
          },
          "sampling": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/CropSampling"
              },
              {
                "type": "null"
              }
            ],
            "description": "The market's sampling rule; null when it sets none (a lot of the crop for this market is then not sampled)."
          },
          "created_at": {
            "type": "number"
          },
          "updated_at": {
            "type": "number"
          }
        }
      },
      "CropMarketRulePut": {
        "type": "object",
        "required": [
          "registration_protocol",
          "sampling"
        ],
        "additionalProperties": false,
        "properties": {
          "registration_protocol": {
            "type": "boolean"
          },
          "sampling": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/CropSampling"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "CropGradingRule": {
        "type": "object",
        "required": [
          "crop",
          "variety",
          "rules",
          "created_at",
          "updated_at"
        ],
        "additionalProperties": false,
        "description": "The platform's grading rules for one variety of a crop, or for every variety of it (`variety` null). They apply to a lot whose company has no grading rules of its own for the lot's variety.",
        "properties": {
          "crop": {
            "type": "string"
          },
          "variety": {
            "type": [
              "string",
              "null"
            ]
          },
          "rules": {
            "$ref": "#/components/schemas/GradingRules"
          },
          "created_at": {
            "type": "number"
          },
          "updated_at": {
            "type": "number"
          }
        }
      },
      "CropGradingRulePut": {
        "type": "object",
        "required": [
          "variety",
          "rules"
        ],
        "additionalProperties": false,
        "properties": {
          "variety": {
            "type": [
              "string",
              "null"
            ],
            "minLength": 1,
            "maxLength": 64,
            "description": "A variety of the crop; null for every variety of it."
          },
          "rules": {
            "$ref": "#/components/schemas/GradingRules"
          }
        }
      },
      "CropDetail": {
        "type": "object",
        "required": [
          "code",
          "names",
          "ripeness_scale",
          "created_at",
          "updated_at",
          "markets",
          "grading_rules"
        ],
        "additionalProperties": false,
        "description": "A crop of the registry with its rules per destination market and its grading rules.",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$",
            "description": "The crop code that lots (`product`) and growing areas (`crop`) name."
          },
          "names": {
            "$ref": "#/components/schemas/CropNames"
          },
          "ripeness_scale": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "levels_1_to_4",
              null
            ],
            "description": "The crop's ripeness scale: `levels_1_to_4`, the four ripeness levels a durian is graded on (1 immature, 2 mature-firm, 3 just ripe, 4 overripe); null when the crop has no ripeness scale."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds (0 for the crop the platform started with)."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds of the last change."
          },
          "markets": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CropMarketRule"
            }
          },
          "grading_rules": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CropGradingRule"
            }
          }
        }
      },
      "OidcStart": {
        "type": "object",
        "description": "#87. The company whose identity provider the person signs in with.",
        "additionalProperties": false,
        "required": [
          "company"
        ],
        "properties": {
          "company": {
            "type": "string",
            "minLength": 1,
            "description": "The company's id."
          }
        },
        "example": {
          "company": "coop-dl"
        }
      },
      "OidcStarted": {
        "type": "object",
        "description": "#87. Where to send the browser: the company's identity provider, with the authorization code flow's parameters (`state`, `nonce`, the PKCE `code_challenge` with method S256, the company's own redirect URI and scope `openid email`). The sign-in must finish (POST /v1/auth/oidc/callback) before `expires_at`, in the same browser.",
        "additionalProperties": false,
        "required": [
          "authorization_url",
          "expires_at"
        ],
        "properties": {
          "authorization_url": {
            "type": "string",
            "format": "uri"
          },
          "expires_at": {
            "type": "number",
            "description": "Unix seconds (10 minutes after the start)."
          }
        },
        "example": {
          "authorization_url": "https://login.coop.example/authorize?response_type=code&client_id=croppath-console&redirect_uri=https%3A%2F%2Ftxng.theio.vn%2Flogin%2Foidc%2Fcoop-dl&scope=openid+email&state=q3Vb0mXl2sQ&nonce=Zx9a&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256",
          "expires_at": 1790087000.0
        }
      },
      "OidcCallback": {
        "type": "object",
        "description": "#87. What the identity provider sent back to the company's redirect URI, and that company.",
        "additionalProperties": false,
        "required": [
          "state",
          "code",
          "company"
        ],
        "properties": {
          "state": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256
          },
          "code": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2048
          },
          "company": {
            "type": "string",
            "minLength": 1,
            "maxLength": 128,
            "description": "The company of the redirect URI the provider sent the browser back to (`{origin}/login/oidc/{company}`); it must be the company the sign-in was started for."
          },
          "iss": {
            "type": "string",
            "maxLength": 512,
            "description": "The `iss` parameter of the provider's redirect (RFC 9207), when it sent one: it must be the provider's issuer."
          }
        },
        "example": {
          "state": "q3Vb0mXl2sQ",
          "code": "SplxlOBeZQQYbYS6WxSbIA",
          "company": "coop-dl",
          "iss": "https://login.coop.example"
        }
      },
      "IdentityProvider": {
        "type": "object",
        "description": "#87. The company's identity provider; never its client secret.",
        "additionalProperties": false,
        "required": [
          "issuer",
          "client_id",
          "enabled",
          "created_at",
          "updated_at",
          "linked_accounts"
        ],
        "properties": {
          "issuer": {
            "type": "string",
            "format": "uri"
          },
          "client_id": {
            "type": "string"
          },
          "enabled": {
            "type": "boolean",
            "description": "Whether the company's people can sign in with it now."
          },
          "created_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "updated_at": {
            "type": "number",
            "description": "Unix seconds."
          },
          "linked_accounts": {
            "type": "integer",
            "minimum": 0,
            "description": "Accounts linked to a subject of the provider (by a first sign-in)."
          }
        },
        "example": {
          "issuer": "https://login.coop.example",
          "client_id": "croppath-console",
          "enabled": true,
          "created_at": 1790086400.0,
          "updated_at": 1790086400.0,
          "linked_accounts": 3
        }
      },
      "IdentityProviderState": {
        "type": "object",
        "description": "#87. The company's identity provider (null when none is set up), the company's own redirect URI to register with it (`{origin}/login/oidc/{company}`; the provider must send the browser back there), and whether this deployment allows sign-in with an identity provider at all (it needs AGRITRACE_PUBLIC_ORIGIN and AGRITRACE_OIDC_ALLOWED_HOSTS).",
        "additionalProperties": false,
        "required": [
          "available",
          "redirect_uri",
          "provider"
        ],
        "properties": {
          "available": {
            "type": "boolean"
          },
          "redirect_uri": {
            "type": [
              "string",
              "null"
            ],
            "description": "Null when the server has no public origin."
          },
          "provider": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/IdentityProvider"
              },
              {
                "type": "null"
              }
            ]
          }
        },
        "example": {
          "available": true,
          "redirect_uri": "https://txng.theio.vn/login/oidc/coop-dl",
          "provider": {
            "issuer": "https://login.coop.example",
            "client_id": "croppath-console",
            "enabled": true,
            "created_at": 1790086400.0,
            "updated_at": 1790086400.0,
            "linked_accounts": 3
          }
        }
      },
      "IdentityProviderUpdate": {
        "type": "object",
        "description": "#87. The company's identity provider as registered there.",
        "additionalProperties": false,
        "required": [
          "issuer",
          "client_id"
        ],
        "properties": {
          "issuer": {
            "type": "string",
            "minLength": 9,
            "maxLength": 512,
            "description": "The provider's issuer: an https:// URL without query or fragment, on a host this deployment allows; `{issuer}/.well-known/openid-configuration` must name it."
          },
          "client_id": {
            "type": "string",
            "minLength": 1,
            "maxLength": 255,
            "pattern": "^[!-~]+$"
          },
          "client_secret": {
            "type": "string",
            "minLength": 1,
            "maxLength": 512,
            "pattern": "^[!-~]+$",
            "description": "Required to set a provider up, and whenever the issuer or the client id changes (400 `client_secret_is_required`); left out otherwise, the stored one is kept. Stored only encrypted and never returned."
          },
          "enabled": {
            "type": "boolean",
            "default": true
          }
        },
        "example": {
          "issuer": "https://login.coop.example",
          "client_id": "croppath-console",
          "client_secret": "s3cret-from-the-idp",
          "enabled": true
        }
      },
      "ResidueCertificate": {
        "type": "object",
        "additionalProperties": false,
        "description": "#157: a lot's lab results judged against its destination market (see getLotResidueCertificate).",
        "required": [
          "lot",
          "product",
          "report",
          "market",
          "market_from",
          "limits_on",
          "verdict",
          "analytes",
          "required_analytes",
          "missing_analytes"
        ],
        "properties": {
          "lot": {
            "type": "string"
          },
          "product": {
            "type": "string"
          },
          "report": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "report_no",
              "lab",
              "market",
              "signed_at",
              "received_at",
              "key_custody",
              "key_revoked_for_compromise"
            ],
            "description": "The lab report; null while the lab has not reported.",
            "properties": {
              "report_no": {
                "type": "string"
              },
              "lab": {
                "type": "string"
              },
              "market": {
                "type": "string",
                "pattern": "^[A-Z]{2}$",
                "description": "The market the lot was sampled for."
              },
              "signed_at": {
                "type": "number",
                "description": "Unix seconds."
              },
              "received_at": {
                "type": "number",
                "description": "Unix seconds."
              },
              "key_custody": {
                "type": "string",
                "enum": [
                  "lab",
                  "server"
                ],
                "description": "lab: the lab signed with its own key; server: a lab portal entry CropPath signed with the key it holds for the lab."
              },
              "key_revoked_for_compromise": {
                "type": "boolean",
                "description": "True once the lab key that signed the report has been revoked for compromise, whenever it signed it: the key no longer vouches for the results, so the report counts as unsigned (as on the public lot record) and the certificate's verdict is never pass."
              }
            }
          },
          "market": {
            "type": [
              "string",
              "null"
            ],
            "pattern": "^[A-Z]{2}$",
            "description": "The destination market the results are judged against."
          },
          "market_from": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "shipment",
              "lot",
              "report",
              null
            ],
            "description": "Where the market comes from: the lot's shipment, the lot's own destination, or the lab report."
          },
          "limits_on": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "description": "The report's signed date (Asia/Ho_Chi_Minh), the day the limits are read for."
          },
          "verdict": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "pass",
              "fail",
              "incomplete",
              null
            ]
          },
          "analytes": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ResidueCertificateAnalyte"
            }
          },
          "required_analytes": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "missing_analytes": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "example": {
          "lot": "LO-260928-014",
          "product": "durian",
          "report": {
            "report_no": "KN-260929-0071",
            "lab": "LAB-VN-118",
            "market": "CN",
            "signed_at": 1790671200.0,
            "received_at": 1790671260.0,
            "key_custody": "lab",
            "key_revoked_for_compromise": false
          },
          "market": "CN",
          "market_from": "report",
          "limits_on": "2026-09-29",
          "verdict": "pass",
          "analytes": [
            {
              "analyte": "cadmium",
              "samples": 3,
              "outcome": "measured",
              "value": 0.018,
              "lod": null,
              "unit": "mg/kg",
              "limit": {
                "kind": "max",
                "value": 0.05,
                "unit": "mg/kg",
                "source": "GB 2762-2022 National food safety standard: maximum levels of contaminants in foods, 4.2 cadmium, fresh fruit 0.05 mg/kg (published 2022-06-30, in force 2023-06-30)",
                "basis": "market_limit"
              },
              "verdict": "pass"
            },
            {
              "analyte": "auramine_o",
              "samples": 3,
              "outcome": "not_detected",
              "value": null,
              "lod": 0.001,
              "unit": "mg/kg",
              "limit": {
                "kind": "banned",
                "value": null,
                "unit": "mg/kg",
                "source": "Auramine O is a non-edible substance in China (Ministry of Health list, 2008): no level is permitted",
                "basis": "market_limit"
              },
              "verdict": "pass"
            }
          ],
          "required_analytes": [
            "cadmium",
            "auramine_o"
          ],
          "missing_analytes": []
        }
      },
      "ResidueCertificateAnalyte": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "analyte",
          "samples",
          "outcome",
          "value",
          "lod",
          "unit",
          "limit",
          "verdict"
        ],
        "properties": {
          "analyte": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$"
          },
          "samples": {
            "type": "integer",
            "minimum": 1,
            "description": "The number of results (one per drawn sample)."
          },
          "outcome": {
            "type": "string",
            "enum": [
              "measured",
              "not_detected"
            ],
            "description": "measured when a sample measured it, else not_detected."
          },
          "value": {
            "type": [
              "number",
              "null"
            ],
            "description": "The highest measured value; null when not detected."
          },
          "lod": {
            "type": [
              "number",
              "null"
            ],
            "description": "The highest detection limit of the results; null when measured."
          },
          "unit": {
            "type": "string",
            "enum": [
              "mg/kg"
            ]
          },
          "limit": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "kind",
              "value",
              "unit",
              "source",
              "basis"
            ],
            "description": "The limit the analyte was judged with; null when the market sets none.",
            "properties": {
              "kind": {
                "type": "string",
                "enum": [
                  "max",
                  "banned"
                ]
              },
              "value": {
                "type": [
                  "number",
                  "null"
                ],
                "exclusiveMinimum": 0,
                "description": "The maximum; null for a ban."
              },
              "unit": {
                "type": "string",
                "enum": [
                  "mg/kg"
                ]
              },
              "source": {
                "type": "string",
                "minLength": 1,
                "maxLength": 1000,
                "description": "The regulation it cites."
              },
              "basis": {
                "type": "string",
                "enum": [
                  "market_limit",
                  "default_limit"
                ],
                "description": "market_limit: the market's own entry for the analyte; default_limit: the market's default limit rule, for a pesticide a source read shows the market sets no specific limit for in the product."
              }
            }
          },
          "verdict": {
            "type": "string",
            "enum": [
              "pass",
              "fail",
              "no_limit"
            ]
          }
        }
      },
      "LotApplications": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "lot",
          "growing_area",
          "from",
          "until",
          "items",
          "more",
          "sprays"
        ],
        "properties": {
          "lot": {
            "type": "string",
            "description": "Lot code."
          },
          "growing_area": {
            "type": [
              "string",
              "null"
            ],
            "description": "The lot's growing area; null: none, and no records."
          },
          "from": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "Start of the period listed (included), UTC; null without a growing area."
          },
          "until": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "End of the period listed (excluded): the end of the lot's harvest day, UTC; null without a growing area."
          },
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/LotApplication"
            }
          },
          "more": {
            "type": "boolean",
            "description": "More records than `items` lists: the older ones were left out."
          },
          "sprays": {
            "type": "array",
            "maxItems": 200,
            "description": "#322: the spray records of the lot's growing area (its spray log, `GET /v1/growing-areas/{code}/sprays`) sprayed from the first day of the period to the harvest day, both included, oldest first (at most 200, the newest kept), each with its withholding status at the harvest day; empty without a growing area. Listed only: they do not hold a harvest.",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "sprayed_on",
                "product",
                "active_ingredient",
                "withholding_days",
                "safe_from",
                "withholding_status"
              ],
              "properties": {
                "id": {
                  "type": "integer"
                },
                "sprayed_on": {
                  "type": "string",
                  "format": "date",
                  "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
                },
                "product": {
                  "type": "string"
                },
                "active_ingredient": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "withholding_days": {
                  "type": "integer",
                  "minimum": 0,
                  "maximum": 365
                },
                "safe_from": {
                  "type": "string",
                  "format": "date",
                  "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
                  "description": "sprayed_on plus withholding_days: the first day a harvest is allowed."
                },
                "withholding_status": {
                  "enum": [
                    "ok",
                    "violated"
                  ],
                  "description": "violated when the harvest day falls from sprayed_on to the day before safe_from."
                }
              }
            }
          }
        }
      },
      "LotApplication": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "applied_at",
          "input",
          "product",
          "product_mass_kg",
          "product_volume_l",
          "duration_s",
          "phi_days",
          "interval_ends_at",
          "status",
          "reasons",
          "device_id",
          "operator",
          "harvest_app"
        ],
        "properties": {
          "id": {
            "type": "string",
            "description": "The application record's envelope id."
          },
          "applied_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the application started (the event's time), UTC."
          },
          "input": {
            "type": [
              "string",
              "null"
            ],
            "description": "`apply.input` as recorded: water, fertiliser, pesticide, lime or light (null when the held record has none)."
          },
          "product": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "id",
              "batch",
              "name"
            ],
            "properties": {
              "id": {
                "type": "string"
              },
              "batch": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "name": {
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "description": "`apply.product`: the product's id (a registration number, GTIN or the farm's own code), batch and trade name when recorded."
          },
          "product_mass_kg": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "description": "`apply.product_mass` in kg, when recorded."
          },
          "product_volume_l": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "description": "`apply.product_volume` in litres, when recorded."
          },
          "duration_s": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "description": "`apply.duration` in seconds, when recorded."
          },
          "phi_days": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "description": "`apply.phi_days`: the pre-harvest interval the product's label gives, in days, as recorded."
          },
          "interval_ends_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "When the pre-harvest interval ends, as the check at harvest reads it (the application's end plus the interval); null when the record states none."
          },
          "status": {
            "type": "string",
            "enum": [
              "accepted",
              "quarantined"
            ],
            "description": "quarantined: held for review."
          },
          "reasons": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Why the record is held (empty when accepted)."
          },
          "device_id": {
            "type": "string",
            "description": "The device or harvest app install that signed it."
          },
          "operator": {
            "type": [
              "string",
              "null"
            ],
            "description": "`context.operator`: who applied it, as the company's opaque id."
          },
          "harvest_app": {
            "type": "boolean",
            "description": "Entered by hand in the harvest app: Self-declared."
          }
        }
      },
      "CompanyUsageQuotas": {
        "type": "object",
        "description": "#134. The company's quotas: its API calls per minute and per UTC day (requests made with its API tokens or API clients; over either, 429 with `Retry-After`), with today's calls, and its device messages per second with a burst (over them the MQTT ingest keeps its messages in its ingest backlog and stores them at that rate; the HTTP ingest answers 429), with the messages waiting in that backlog.",
        "required": [
          "api_per_minute",
          "api_per_day",
          "api_calls_today",
          "api_day_warning",
          "api_day_reached",
          "ingest_per_second",
          "ingest_burst",
          "ingest_backlog"
        ],
        "additionalProperties": false,
        "properties": {
          "api_per_minute": {
            "type": "integer",
            "minimum": 1,
            "description": "API calls a minute; over it, 429 with `Retry-After`."
          },
          "api_per_day": {
            "type": "integer",
            "minimum": 1,
            "description": "API calls a UTC day; once reached, 429 until the next UTC midnight."
          },
          "api_calls_today": {
            "type": "integer",
            "minimum": 0,
            "description": "API calls counted this UTC day (as `api_calls`' first day)."
          },
          "api_day_warning": {
            "type": "boolean",
            "description": "`api_calls_today` is at least `warn_percent` of `api_per_day`."
          },
          "api_day_reached": {
            "type": "boolean",
            "description": "`api_calls_today` reached `api_per_day`: further calls today are refused."
          },
          "ingest_per_second": {
            "type": "integer",
            "minimum": 1,
            "description": "Device messages a second the ingest stores as they arrive."
          },
          "ingest_burst": {
            "type": "integer",
            "minimum": 1,
            "description": "Device messages the ingest stores at once above that rate after a quiet period."
          },
          "ingest_backlog": {
            "type": "integer",
            "minimum": 0,
            "description": "Device messages waiting in the company's ingest backlog."
          }
        },
        "example": {
          "api_per_minute": 1200,
          "api_per_day": 500000,
          "api_calls_today": 1520,
          "api_day_warning": false,
          "api_day_reached": false,
          "ingest_per_second": 100,
          "ingest_burst": 3000,
          "ingest_backlog": 0
        },
        "x-not-in-sdk": true
      },
      "CompanyUsageStored": {
        "type": "object",
        "description": "#134. What the company keeps, counts only (no quota applies to them): its device messages stored, the public scans of its fruits still kept, and its stored files (attachments uploaded for its devices' envelopes and documents its users uploaded) with their total size. Files are content-addressed and shared, so a file two companies hold counts for each; database rows are not counted in `storage_bytes`.",
        "required": [
          "envelopes",
          "scans",
          "attachments",
          "storage_bytes"
        ],
        "additionalProperties": false,
        "properties": {
          "envelopes": {
            "type": "integer",
            "minimum": 0,
            "description": "Device messages (envelopes) stored for the company, of every status."
          },
          "scans": {
            "type": "integer",
            "minimum": 0,
            "description": "Public scans of the company's fruits still kept (each fruit's scan counter, which keeps its count after the raw scan rows expire)."
          },
          "attachments": {
            "type": "integer",
            "minimum": 0,
            "description": "Files stored: device attachments uploaded for the company's envelopes plus documents its users uploaded."
          },
          "storage_bytes": {
            "type": "integer",
            "minimum": 0,
            "description": "The total size of those files, in bytes."
          }
        },
        "example": {
          "envelopes": 184220,
          "scans": 52310,
          "attachments": 1730,
          "storage_bytes": 412876800
        },
        "x-not-in-sdk": true
      },
      "StationSignInRequest": {
        "type": "object",
        "additionalProperties": false,
        "description": "#85: a station sign-in; `lifetime_s` its length (default the most, one shift).",
        "properties": {
          "lifetime_s": {
            "type": "integer",
            "minimum": 900,
            "maximum": 28800
          }
        }
      },
      "StationDelegation": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "gateway",
          "operator",
          "state",
          "issued_at",
          "code_expires_at",
          "expires_at",
          "claimed_at",
          "revoked_at"
        ],
        "description": "#85: a station sign-in (Unix times).",
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$"
          },
          "gateway": {
            "type": "string"
          },
          "operator": {
            "type": "string",
            "description": "The operator's opaque id (`user-<id>`)."
          },
          "state": {
            "type": "string",
            "enum": [
              "pending",
              "unclaimed",
              "active",
              "expired",
              "revoked"
            ],
            "description": "pending: the code not typed yet; unclaimed: the code expired unused; active: claimed by the station; expired: past `expires_at`; revoked."
          },
          "issued_at": {
            "type": "number"
          },
          "code_expires_at": {
            "type": "number"
          },
          "expires_at": {
            "type": "number"
          },
          "claimed_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          }
        }
      },
      "StationSignIn": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "gateway",
          "operator",
          "state",
          "issued_at",
          "code_expires_at",
          "expires_at",
          "claimed_at",
          "revoked_at",
          "code"
        ],
        "description": "#85: a new station sign-in with its one-time code (shown only in this answer).",
        "properties": {
          "id": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$"
          },
          "gateway": {
            "type": "string"
          },
          "operator": {
            "type": "string",
            "description": "The operator's opaque id (`user-<id>`)."
          },
          "state": {
            "type": "string",
            "enum": [
              "pending",
              "unclaimed",
              "active",
              "expired",
              "revoked"
            ],
            "description": "pending: the code not typed yet; unclaimed: the code expired unused; active: claimed by the station; expired: past `expires_at`; revoked."
          },
          "issued_at": {
            "type": "number"
          },
          "code_expires_at": {
            "type": "number"
          },
          "expires_at": {
            "type": "number"
          },
          "claimed_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "code": {
            "type": "string",
            "pattern": "^[A-HJ-KMNP-Z2-9]{8}$",
            "description": "Typed on the station's screen within 10 minutes."
          }
        }
      },
      "StationDelegationList": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/StationDelegation"
            }
          }
        }
      },
      "StationSignature": {
        "type": "object",
        "required": [
          "alg",
          "kid",
          "value"
        ],
        "additionalProperties": false,
        "description": "ES256 over the canonical JSON of every member but `sig` (an envelope's signature).",
        "properties": {
          "alg": {
            "const": "ES256"
          },
          "kid": {
            "type": "string"
          },
          "value": {
            "type": "string"
          }
        }
      },
      "StationClaimRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "gateway",
          "time",
          "code",
          "sig"
        ],
        "properties": {
          "gateway": {
            "type": "string"
          },
          "time": {
            "type": "string",
            "format": "date-time",
            "description": "The station's time, ISO 8601 with a zone offset."
          },
          "code": {
            "type": "string",
            "maxLength": 32
          },
          "sig": {
            "$ref": "#/components/schemas/StationSignature"
          }
        }
      },
      "StationLabel": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "lot",
          "n",
          "round",
          "status",
          "qr_url"
        ],
        "description": "What the station's printer queue prints a fruit's 40 x 30 mm label from (#66, #92).",
        "properties": {
          "code": {
            "type": "string"
          },
          "lot": {
            "type": "string"
          },
          "n": {
            "type": "integer"
          },
          "round": {
            "type": "integer",
            "description": "The fruit's measurement round."
          },
          "status": {
            "type": "string"
          },
          "qr_url": {
            "type": "string",
            "format": "uri"
          },
          "label_code": {
            "type": "string",
            "pattern": "^[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}$",
            "description": "#326, with `label_code=1` only: the fruit's lookup code (#288) in its grouped form (three groups of five Crockford base 32 characters), derived from the fruit's public id. The station's fruit label prints it beside the QR code; a person types it on the scan page when the QR code cannot be scanned, and `GET /v1/public/resolve` answers it with the fruit.",
            "example": "7YD1R-1YMWA-W5MVB",
            "x-not-in-sdk": true
          }
        }
      },
      "StationClaim": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "delegation",
          "labels",
          "last_seq",
          "time"
        ],
        "properties": {
          "delegation": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "id",
              "operator",
              "name",
              "issued_at",
              "claimed_at",
              "expires_at"
            ],
            "properties": {
              "id": {
                "type": "string"
              },
              "operator": {
                "type": "string"
              },
              "name": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "issued_at": {
                "type": "number"
              },
              "claimed_at": {
                "type": "number"
              },
              "expires_at": {
                "type": "number"
              }
            }
          },
          "labels": {
            "type": "array",
            "maxItems": 2000,
            "items": {
              "$ref": "#/components/schemas/StationLabel"
            }
          },
          "last_seq": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The highest `seq` the cloud recorded from the station (null before its first action): the station's action counter moves above it before it records."
          },
          "time": {
            "type": "number",
            "description": "The cloud's time (Unix seconds): the station counts the delegation's end from it on its monotonic clock."
          }
        }
      },
      "StationSyncRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "gateway",
          "time",
          "sig"
        ],
        "properties": {
          "gateway": {
            "type": "string"
          },
          "time": {
            "type": "string",
            "format": "date-time",
            "description": "The station's time, ISO 8601 with a zone offset."
          },
          "delegations": {
            "type": "array",
            "maxItems": 64,
            "items": {
              "type": "string",
              "pattern": "^[0-9a-f]{32}$"
            }
          },
          "sig": {
            "$ref": "#/components/schemas/StationSignature"
          }
        }
      },
      "StationSync": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "delegations",
          "labels",
          "last_seq",
          "time"
        ],
        "properties": {
          "delegations": {
            "type": "object",
            "additionalProperties": {
              "type": "string",
              "enum": [
                "active",
                "revoked",
                "expired",
                "unknown"
              ]
            }
          },
          "labels": {
            "type": "array",
            "maxItems": 2000,
            "items": {
              "$ref": "#/components/schemas/StationLabel"
            }
          },
          "last_seq": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The highest `seq` the cloud recorded from the station (null before its first action)."
          },
          "time": {
            "type": "number"
          }
        }
      },
      "StationActionRecord": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "v",
          "id",
          "type",
          "gateway",
          "seq",
          "delegation",
          "operator",
          "fruit",
          "recorded_at",
          "sig"
        ],
        "description": "#85: an operator's action recorded offline at an edge station, signed with the station's key.",
        "properties": {
          "v": {
            "const": 1
          },
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "type": "string",
            "enum": [
              "accept",
              "remeasure",
              "print"
            ]
          },
          "gateway": {
            "type": "string"
          },
          "seq": {
            "type": "integer",
            "minimum": 0,
            "description": "The station's action counter: replay order."
          },
          "delegation": {
            "type": "string",
            "pattern": "^[0-9a-f]{32}$"
          },
          "operator": {
            "type": "string",
            "pattern": "^user-[1-9][0-9]{0,17}$"
          },
          "fruit": {
            "type": "string"
          },
          "round": {
            "type": "integer",
            "minimum": 1,
            "description": "A re-measure only: the round the station numbered."
          },
          "recorded_at": {
            "type": "string",
            "format": "date-time",
            "description": "The station's time, ISO 8601 with a zone offset."
          },
          "time_source": {
            "type": "string",
            "enum": [
              "gnss",
              "ntp",
              "unsynced"
            ],
            "description": "The station's clock state. `unsynced` (the station found its clock off): the action is placed in the delegation by `since_claim_s` alone, and refused (403 `unsynced_clock`) without it."
          },
          "since_claim_s": {
            "type": "integer",
            "description": "Whole seconds (0 to 2^31 - 1) since the station claimed the delegation, by its monotonic clock, rounded up; above the delegation's length plus 300 s the action is refused (403 `delegation_expired`), whatever `recorded_at` says."
          },
          "after": {
            "type": "array",
            "maxItems": 16,
            "items": {
              "type": "string",
              "format": "uuid"
            },
            "description": "The fruit's envelopes the station recorded before the action."
          },
          "sig": {
            "$ref": "#/components/schemas/StationSignature"
          }
        }
      },
      "StationActionResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "type",
          "outcome",
          "seq",
          "fruit"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "type": {
            "type": "string",
            "enum": [
              "accept",
              "remeasure",
              "print"
            ]
          },
          "outcome": {
            "type": "string",
            "enum": [
              "applied"
            ]
          },
          "seq": {
            "type": "integer"
          },
          "fruit": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "status": {
                "type": "string"
              },
              "accepted_at": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "round": {
                "type": "integer"
              }
            }
          }
        }
      },
      "EmailSettings": {
        "type": "object",
        "required": [
          "notifications",
          "language",
          "delivery"
        ],
        "additionalProperties": false,
        "properties": {
          "notifications": {
            "type": "boolean",
            "description": "Whether the person gets the notification, alert and recall emails (on until they turn it off). Invitation and password emails are always sent."
          },
          "language": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "vi",
              "en",
              "zh-Hans",
              null
            ],
            "description": "The language of the person's emails; null: not known, an email then carries Vietnamese, English and Simplified Chinese."
          },
          "delivery": {
            "type": "boolean",
            "description": "Whether this server sends email at all (SMTP configured). When false, one-time links are passed on by hand; when true, each one-time link is also emailed to its person."
          }
        },
        "example": {
          "notifications": true,
          "language": "vi",
          "delivery": false
        }
      },
      "EmailSettingsUpdate": {
        "type": "object",
        "required": [
          "notifications"
        ],
        "additionalProperties": false,
        "properties": {
          "notifications": {
            "type": "boolean"
          },
          "language": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "vi",
              "en",
              "zh-Hans",
              null
            ],
            "description": "Omitted or null: not known."
          }
        },
        "example": {
          "notifications": false,
          "language": "en"
        }
      },
      "EmailUnsubscribe": {
        "type": "object",
        "required": [
          "token"
        ],
        "additionalProperties": false,
        "properties": {
          "token": {
            "type": "string",
            "maxLength": 200,
            "description": "The token of the email's link (`/login#unsubscribe=<token>`)."
          }
        },
        "example": {
          "token": "12.coop-dl.4yGq3o0b1d0e7n2m8J5k9v6c3x1z0a2s4d6f8h0j2l4"
        }
      },
      "EmailUnsubscribed": {
        "type": "object",
        "required": [
          "notifications"
        ],
        "additionalProperties": false,
        "properties": {
          "notifications": {
            "type": "boolean",
            "const": false
          }
        },
        "example": {
          "notifications": false
        }
      },
      "AdminUnitProvince": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "name",
          "kind"
        ],
        "description": "A province-level unit: a province (tỉnh) or a centrally governed city (thành phố trung ương).",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[0-9]{2}$",
            "description": "Its 2-digit official code."
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "description": "Its official name, with its unit word (\"Tỉnh\", \"Thành phố\"), in Vietnamese."
          },
          "kind": {
            "type": "string",
            "enum": [
              "tỉnh",
              "thành phố trung ương"
            ]
          }
        }
      },
      "AdminUnitCommune": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "name",
          "kind"
        ],
        "description": "A commune-level unit: a commune (xã), a ward (phường) or a special zone (đặc khu).",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[0-9]{5}$",
            "description": "Its 5-digit official code."
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "description": "Its official name, with its unit word (\"Xã\", \"Phường\", \"Đặc khu\"), in Vietnamese."
          },
          "kind": {
            "type": "string",
            "enum": [
              "xã",
              "phường",
              "đặc khu"
            ]
          }
        }
      },
      "AdminUnitSource": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "publisher",
          "url"
        ],
        "description": "Who publishes the official list, credited with it.",
        "properties": {
          "publisher": {
            "type": "string"
          },
          "url": {
            "type": "string",
            "format": "uri"
          }
        }
      },
      "AdminUnitProvinces": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "version",
          "valid_from",
          "source",
          "provinces"
        ],
        "description": "The provinces of one catalog version, by code.",
        "properties": {
          "version": {
            "type": "string",
            "pattern": "^vn-[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The catalog version: `vn-` and the date of the official list it holds. Store it with every code taken from it."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "description": "The day from which this version is the one for new input: the effective date of the newest resolution it reflects."
          },
          "source": {
            "$ref": "#/components/schemas/AdminUnitSource"
          },
          "provinces": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AdminUnitProvince"
            }
          }
        }
      },
      "AdminUnitCommunes": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "version",
          "valid_from",
          "source",
          "province",
          "communes"
        ],
        "description": "One province of a catalog version and its communes, by code.",
        "properties": {
          "version": {
            "type": "string",
            "pattern": "^vn-[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The catalog version: `vn-` and the date of the official list it holds. Store it with every code taken from it."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "description": "The day from which this version is the one for new input: the effective date of the newest resolution it reflects."
          },
          "source": {
            "$ref": "#/components/schemas/AdminUnitSource"
          },
          "province": {
            "$ref": "#/components/schemas/AdminUnitProvince"
          },
          "communes": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AdminUnitCommune"
            }
          }
        }
      },
      "OverviewSectionUnavailable": {
        "type": "object",
        "description": "#274. A section of an overview that could not be read: one of its queries failed. Only that section fails; the other sections answer.",
        "additionalProperties": false,
        "required": [
          "state",
          "reason"
        ],
        "properties": {
          "state": {
            "const": "unavailable"
          },
          "reason": {
            "type": "string",
            "enum": [
              "query_failed"
            ]
          }
        },
        "example": {
          "state": "unavailable",
          "reason": "query_failed"
        }
      },
      "CompanyOverviewAlerts": {
        "description": "#274. The company's open alerts.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "open",
              "open_high"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "open": {
                "type": "integer",
                "minimum": 0,
                "description": "Open alerts of every severity."
              },
              "open_high": {
                "type": "integer",
                "minimum": 0,
                "description": "Open alerts of severity high."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "open": 7,
          "open_high": 2
        }
      },
      "CompanyOverviewQuarantine": {
        "description": "#274. Device messages waiting for review (quarantined).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "waiting",
              "capped",
              "oldest_received_at"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "waiting": {
                "type": "integer",
                "minimum": 0,
                "description": "At most 10,000."
              },
              "capped": {
                "type": "boolean",
                "description": "More than 10,000 wait: `waiting` is 10,000."
              },
              "oldest_received_at": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time",
                "description": "When the oldest waiting message was received; null when none waits."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "waiting": 3,
          "capped": false,
          "oldest_received_at": "2026-10-16T22:10:00Z"
        }
      },
      "CompanyOverviewRecalls": {
        "description": "#274. Recalled and withdrawn lots and the recall notices not yet delivered.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "recalled",
              "withdrawn",
              "notices_pending"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "recalled": {
                "type": "integer",
                "minimum": 0,
                "description": "Lots with status recalled."
              },
              "withdrawn": {
                "type": "integer",
                "minimum": 0,
                "description": "Lots with status withdrawn."
              },
              "notices_pending": {
                "type": "integer",
                "minimum": 0,
                "description": "Recall notices to the authorities not yet delivered."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "recalled": 0,
          "withdrawn": 1,
          "notices_pending": 0
        }
      },
      "CompanyOverviewFleet": {
        "description": "#274. The company's devices and gateways.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "devices_active",
              "devices_ready",
              "devices_not_ready",
              "devices_pending_approval",
              "gateways_active",
              "gateways_silent",
              "calibrations_expired",
              "calibrations_expiring",
              "harvest_keys_pending"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "devices_active": {
                "type": "integer",
                "minimum": 0,
                "description": "Active devices."
              },
              "devices_ready": {
                "type": "integer",
                "minimum": 0,
                "description": "Active devices with a message within 24 hours and a key that may sign."
              },
              "devices_not_ready": {
                "type": "integer",
                "minimum": 0,
                "description": "`devices_active` minus `devices_ready`."
              },
              "devices_pending_approval": {
                "type": "integer",
                "minimum": 0,
                "description": "Devices waiting for CropPath's approval."
              },
              "gateways_active": {
                "type": "integer",
                "minimum": 0,
                "description": "Active gateways."
              },
              "gateways_silent": {
                "type": "integer",
                "minimum": 0,
                "description": "Active gateways without a heartbeat within 24 hours."
              },
              "calibrations_expired": {
                "type": "integer",
                "minimum": 0,
                "description": "Active devices whose current calibration has ended."
              },
              "calibrations_expiring": {
                "type": "integer",
                "minimum": 0,
                "description": "Active devices whose current calibration ends within 30 days."
              },
              "harvest_keys_pending": {
                "type": "integer",
                "minimum": 0,
                "description": "Harvest app keys waiting for approval."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "devices_active": 42,
          "devices_ready": 39,
          "devices_not_ready": 3,
          "devices_pending_approval": 1,
          "gateways_active": 4,
          "gateways_silent": 0,
          "calibrations_expired": 0,
          "calibrations_expiring": 2,
          "harvest_keys_pending": 0
        }
      },
      "CompanyOverviewCertifications": {
        "description": "#274. The growing areas' certifications (the latest of each area and scheme: a renewal replaces the older one).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "expired",
              "expiring"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "expired": {
                "type": "integer",
                "minimum": 0,
                "description": "Certifications whose last valid day has passed (Vietnam date)."
              },
              "expiring": {
                "type": "integer",
                "minimum": 0,
                "description": "Certifications ending within 60 days."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "expired": 0,
          "expiring": 1
        }
      },
      "CompanyOverviewToday": {
        "description": "#274. Today's work, `day` of the answer (the Vietnam calendar day).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "lots_created",
              "lots_capped",
              "harvest_kg",
              "harvest_areas",
              "messages",
              "messages_capped",
              "sessions_count",
              "sessions_open"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "lots_created": {
                "type": "integer",
                "minimum": 0,
                "description": "Lots created today, at most 500."
              },
              "lots_capped": {
                "type": "boolean",
                "description": "More than 500: `lots_created` is 500."
              },
              "harvest_kg": {
                "type": "number",
                "minimum": 0,
                "description": "Harvest declared for today, in kg."
              },
              "harvest_areas": {
                "type": "integer",
                "minimum": 0,
                "description": "Growing areas with a harvest declared for today."
              },
              "messages": {
                "type": "integer",
                "minimum": 0,
                "description": "Device messages received today, at most 100,000."
              },
              "messages_capped": {
                "type": "boolean",
                "description": "More than 100,000: `messages` is 100,000."
              },
              "sessions_count": {
                "type": "integer",
                "minimum": 0,
                "description": "Measuring sessions open or paused now (one line each)."
              },
              "sessions_open": {
                "type": "array",
                "maxItems": 5,
                "description": "The 5 most recently opened of them.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "lot",
                    "facility",
                    "line"
                  ],
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "lot": {
                      "type": "string",
                      "description": "The lot's code."
                    },
                    "facility": {
                      "type": "string"
                    },
                    "line": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "lots_created": 6,
          "lots_capped": false,
          "harvest_kg": 1840.5,
          "harvest_areas": 3,
          "messages": 51230,
          "messages_capped": false,
          "sessions_count": 1,
          "sessions_open": [
            {
              "id": "ses-01",
              "lot": "L-2026-0412",
              "facility": "ph1",
              "line": "1"
            }
          ]
        }
      },
      "CompanyOverviewLots": {
        "description": "#274. The company's lots per status.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "by_status"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "by_status": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "draft",
                  "open",
                  "paused",
                  "closed",
                  "packed",
                  "shipped",
                  "recalled",
                  "withdrawn"
                ],
                "properties": {
                  "draft": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "open": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "paused": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "closed": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "packed": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "shipped": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "recalled": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "withdrawn": {
                    "type": "integer",
                    "minimum": 0
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "by_status": {
            "draft": 1,
            "open": 2,
            "paused": 0,
            "closed": 5,
            "packed": 9,
            "shipped": 120,
            "recalled": 0,
            "withdrawn": 1
          }
        }
      },
      "CompanyOverviewShipments": {
        "description": "#274. The company's shipments.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "open",
              "departed_7d",
              "recent_open"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "open": {
                "type": "integer",
                "minimum": 0,
                "description": "Shipments not yet departed."
              },
              "departed_7d": {
                "type": "integer",
                "minimum": 0,
                "description": "Shipments departed within 7 days."
              },
              "recent_open": {
                "type": "array",
                "maxItems": 5,
                "description": "The 5 newest open shipments.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "created_at"
                  ],
                  "properties": {
                    "code": {
                      "type": "string"
                    },
                    "created_at": {
                      "type": "string",
                      "format": "date-time",
                      "description": "When the shipment was created."
                    }
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "open": 2,
          "departed_7d": 5,
          "recent_open": [
            {
              "code": "SHP-0091",
              "created_at": "2026-10-16T03:00:00Z"
            }
          ]
        }
      },
      "CompanyOverviewRequests": {
        "description": "#274. Requests waiting for the company. `personal_data_open` is in the admin view only.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "public_reports_open",
              "grower_requests_open",
              "grower_requests_due_soon"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "public_reports_open": {
                "type": "integer",
                "minimum": 0,
                "description": "Mismatch reports from the public, open."
              },
              "grower_requests_open": {
                "type": "integer",
                "minimum": 0,
                "description": "Grower data requests, open."
              },
              "grower_requests_due_soon": {
                "type": "integer",
                "minimum": 0,
                "description": "Open grower data requests due within 7 days (or overdue)."
              },
              "personal_data_open": {
                "type": "integer",
                "minimum": 0,
                "description": "Personal data requests from members, open (admin view only)."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "public_reports_open": 0,
          "grower_requests_open": 1,
          "grower_requests_due_soon": 0,
          "personal_data_open": 0
        }
      },
      "CompanyOverviewApprovals": {
        "description": "#274. Changes waiting for a second admin (admin view only).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "second_admin_waiting"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "second_admin_waiting": {
                "type": "integer",
                "minimum": 0,
                "description": "Second admin approval requests waiting for a decision."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "second_admin_waiting": 0
        }
      },
      "CompanyOverviewTeam": {
        "description": "#274. The company's people (admin view only).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "members_active",
              "invitations_pending",
              "invitations_expiring"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "members_active": {
                "type": "integer",
                "minimum": 0,
                "description": "Active members."
              },
              "invitations_pending": {
                "type": "integer",
                "minimum": 0,
                "description": "Invitations not yet accepted, revoked or expired."
              },
              "invitations_expiring": {
                "type": "integer",
                "minimum": 0,
                "description": "Of them, those expiring within 2 days."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "members_active": 9,
          "invitations_pending": 2,
          "invitations_expiring": 1
        }
      },
      "CompanyOverviewIntegrations": {
        "description": "#274. The company's webhooks (admin view only).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "webhooks_disabled"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "webhooks_disabled": {
                "type": "integer",
                "minimum": 0,
                "description": "Webhook subscriptions turned off after delivery failures."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "webhooks_disabled": 0
        }
      },
      "CompanyOverviewEmail": {
        "description": "#274. Emails of the company that could not be sent (admin view only).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "failed_24h",
              "failed_kinds"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "failed_24h": {
                "type": "integer",
                "minimum": 0,
                "description": "Emails that failed within 24 hours."
              },
              "failed_kinds": {
                "type": "array",
                "description": "The kinds of those emails, sorted, each once.",
                "items": {
                  "type": "string",
                  "enum": [
                    "alert",
                    "invite",
                    "notification",
                    "recall",
                    "reset"
                  ]
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "failed_24h": 0,
          "failed_kinds": []
        }
      },
      "CompanyOverviewApiDay": {
        "type": "object",
        "description": "#274. The company's daily API call quota and today's calls (UTC day) against it.",
        "additionalProperties": false,
        "required": [
          "api_per_day",
          "api_calls_today",
          "api_day_warning",
          "api_day_reached"
        ],
        "properties": {
          "api_per_day": {
            "type": "integer",
            "minimum": 1,
            "description": "API calls a UTC day."
          },
          "api_calls_today": {
            "type": "integer",
            "minimum": 0,
            "description": "API calls counted this UTC day."
          },
          "api_day_warning": {
            "type": "boolean",
            "description": "`api_calls_today` is at least 80% of `api_per_day`."
          },
          "api_day_reached": {
            "type": "boolean",
            "description": "`api_calls_today` reached `api_per_day`."
          }
        },
        "example": {
          "api_per_day": 500000,
          "api_calls_today": 1200,
          "api_day_warning": false,
          "api_day_reached": false
        }
      },
      "CompanyOverviewUsage": {
        "description": "#274. The company's limits, its daily API call quota and its API calls per day, as `getCompanyUsage` counts them (without what it stores).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "limits",
              "quotas",
              "api_calls"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "limits": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/CompanyUsageLimit"
                },
                "description": "Every limit, in a fixed order."
              },
              "quotas": {
                "$ref": "#/components/schemas/CompanyOverviewApiDay"
              },
              "api_calls": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/CompanyApiCallDay"
                },
                "description": "The last 14 UTC days, newest first, today included."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "limits": [
            {
              "id": "members",
              "used": 9,
              "limit": 200,
              "warning": false,
              "reached": false
            }
          ],
          "quotas": {
            "api_per_day": 500000,
            "api_calls_today": 1200,
            "api_day_warning": false,
            "api_day_reached": false
          },
          "api_calls": [
            {
              "day": "2026-10-17",
              "calls": 1200
            }
          ]
        }
      },
      "CompanyOverview": {
        "type": "object",
        "description": "#274. The selected company's overview for the admin home: what needs attention, today's work, its lots and shipments, its devices and gateways, its people and its usage; counts and the company's own codes only. `view` admin: every section; `view` auditor (a caller who is no admin): without `approvals`, `team`, `integrations`, `email` and `requests.personal_data_open` (absent, not zero). Each section has `state`: `ok` with its figures, or `unavailable` (OverviewSectionUnavailable) when it could not be read.",
        "additionalProperties": false,
        "required": [
          "tenant",
          "generated_at",
          "max_age_s",
          "day",
          "view",
          "sections"
        ],
        "properties": {
          "tenant": {
            "type": "string",
            "description": "The selected company."
          },
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it for up to `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "minimum": 0,
            "description": "Seconds the server serves one answer."
          },
          "day": {
            "type": "object",
            "description": "The day `today` counts in: the Vietnam calendar day (UTC+7). The API call figures keep the UTC day.",
            "additionalProperties": false,
            "required": [
              "date",
              "starts_at",
              "time_zone"
            ],
            "properties": {
              "date": {
                "type": "string",
                "format": "date"
              },
              "starts_at": {
                "type": "string",
                "format": "date-time",
                "description": "Its start (00:00 in Vietnam), in UTC."
              },
              "time_zone": {
                "type": "string",
                "enum": [
                  "Asia/Ho_Chi_Minh"
                ]
              }
            }
          },
          "view": {
            "type": "string",
            "enum": [
              "admin",
              "auditor"
            ]
          },
          "sections": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "alerts",
              "quarantine",
              "recalls",
              "fleet",
              "certifications",
              "today",
              "lots",
              "shipments",
              "requests",
              "usage"
            ],
            "properties": {
              "alerts": {
                "$ref": "#/components/schemas/CompanyOverviewAlerts"
              },
              "quarantine": {
                "$ref": "#/components/schemas/CompanyOverviewQuarantine"
              },
              "recalls": {
                "$ref": "#/components/schemas/CompanyOverviewRecalls"
              },
              "fleet": {
                "$ref": "#/components/schemas/CompanyOverviewFleet"
              },
              "certifications": {
                "$ref": "#/components/schemas/CompanyOverviewCertifications"
              },
              "today": {
                "$ref": "#/components/schemas/CompanyOverviewToday"
              },
              "lots": {
                "$ref": "#/components/schemas/CompanyOverviewLots"
              },
              "shipments": {
                "$ref": "#/components/schemas/CompanyOverviewShipments"
              },
              "requests": {
                "$ref": "#/components/schemas/CompanyOverviewRequests"
              },
              "approvals": {
                "$ref": "#/components/schemas/CompanyOverviewApprovals"
              },
              "team": {
                "$ref": "#/components/schemas/CompanyOverviewTeam"
              },
              "integrations": {
                "$ref": "#/components/schemas/CompanyOverviewIntegrations"
              },
              "email": {
                "$ref": "#/components/schemas/CompanyOverviewEmail"
              },
              "usage": {
                "$ref": "#/components/schemas/CompanyOverviewUsage"
              }
            }
          }
        },
        "example": {
          "tenant": "coop-dl",
          "generated_at": "2026-10-17T07:32:05Z",
          "max_age_s": 30,
          "day": {
            "date": "2026-10-17",
            "starts_at": "2026-10-16T17:00:00Z",
            "time_zone": "Asia/Ho_Chi_Minh"
          },
          "view": "admin",
          "sections": {
            "alerts": {
              "state": "ok",
              "open": 7,
              "open_high": 2
            },
            "quarantine": {
              "state": "ok",
              "waiting": 3,
              "capped": false,
              "oldest_received_at": "2026-10-16T22:10:00Z"
            },
            "recalls": {
              "state": "ok",
              "recalled": 0,
              "withdrawn": 1,
              "notices_pending": 0
            },
            "fleet": {
              "state": "ok",
              "devices_active": 42,
              "devices_ready": 39,
              "devices_not_ready": 3,
              "devices_pending_approval": 1,
              "gateways_active": 4,
              "gateways_silent": 0,
              "calibrations_expired": 0,
              "calibrations_expiring": 2,
              "harvest_keys_pending": 0
            },
            "certifications": {
              "state": "ok",
              "expired": 0,
              "expiring": 1
            },
            "today": {
              "state": "ok",
              "lots_created": 6,
              "lots_capped": false,
              "harvest_kg": 1840.5,
              "harvest_areas": 3,
              "messages": 51230,
              "messages_capped": false,
              "sessions_count": 1,
              "sessions_open": [
                {
                  "id": "ses-01",
                  "lot": "L-2026-0412",
                  "facility": "ph1",
                  "line": "1"
                }
              ]
            },
            "lots": {
              "state": "ok",
              "by_status": {
                "draft": 1,
                "open": 2,
                "paused": 0,
                "closed": 5,
                "packed": 9,
                "shipped": 120,
                "recalled": 0,
                "withdrawn": 1
              }
            },
            "shipments": {
              "state": "ok",
              "open": 2,
              "departed_7d": 5,
              "recent_open": [
                {
                  "code": "SHP-0091",
                  "created_at": "2026-10-16T03:00:00Z"
                }
              ]
            },
            "requests": {
              "state": "ok",
              "public_reports_open": 0,
              "grower_requests_open": 1,
              "grower_requests_due_soon": 0,
              "personal_data_open": 0
            },
            "approvals": {
              "state": "ok",
              "second_admin_waiting": 0
            },
            "team": {
              "state": "ok",
              "members_active": 9,
              "invitations_pending": 2,
              "invitations_expiring": 1
            },
            "integrations": {
              "state": "ok",
              "webhooks_disabled": 0
            },
            "email": {
              "state": "ok",
              "failed_24h": 0,
              "failed_kinds": []
            },
            "usage": {
              "state": "ok",
              "limits": [
                {
                  "id": "members",
                  "used": 9,
                  "limit": 200,
                  "warning": false,
                  "reached": false
                }
              ],
              "quotas": {
                "api_per_day": 500000,
                "api_calls_today": 1200,
                "api_day_warning": false,
                "api_day_reached": false
              },
              "api_calls": [
                {
                  "day": "2026-10-17",
                  "calls": 1200
                }
              ]
            }
          }
        }
      },
      "PlatformOverviewHealth": {
        "description": "#274. The service's health, as `getAdminHealth` reports it, with the last integrity anchor, the last evidence archive and the platform's own open alerts.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "read_only",
              "warnings",
              "db",
              "mqtt",
              "certificates",
              "tsa",
              "issuer_keys",
              "anchor_last_day",
              "evidence_archive",
              "platform_alerts_open",
              "platform_alerts_open_high"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "read_only": {
                "type": "boolean",
                "description": "This process answers 503 to every write."
              },
              "warnings": {
                "type": "array",
                "items": {
                  "type": "string"
                }
              },
              "db": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "dialect",
                  "schema_version",
                  "expected_schema_version",
                  "round_trip_ms"
                ],
                "properties": {
                  "dialect": {
                    "type": "string",
                    "enum": [
                      "sqlite",
                      "postgresql"
                    ]
                  },
                  "schema_version": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "expected_schema_version": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "The version this backend release migrates to."
                  },
                  "round_trip_ms": {
                    "type": "number",
                    "minimum": 0
                  }
                }
              },
              "mqtt": {
                "description": "This process's MQTT bridge; null without one.",
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "connected",
                      "subscribed"
                    ],
                    "properties": {
                      "connected": {
                        "type": "boolean"
                      },
                      "subscribed": {
                        "type": "boolean"
                      }
                    }
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "certificates": {
                "type": "array",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "name",
                    "not_after",
                    "days_left"
                  ],
                  "properties": {
                    "name": {
                      "type": "string",
                      "description": "The certificate's subject."
                    },
                    "not_after": {
                      "type": "string",
                      "format": "date-time",
                      "description": "Its expiry."
                    },
                    "days_left": {
                      "type": "integer",
                      "description": "Whole days to its expiry (negative once expired)."
                    }
                  }
                }
              },
              "tsa": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "mode",
                  "pending",
                  "failing"
                ],
                "properties": {
                  "mode": {
                    "type": "string",
                    "enum": [
                      "on",
                      "off"
                    ]
                  },
                  "pending": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Seals waiting for an external timestamp."
                  },
                  "failing": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Of them, those whose last attempt failed."
                  }
                }
              },
              "issuer_keys": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "available"
                ],
                "properties": {
                  "available": {
                    "type": "boolean"
                  }
                }
              },
              "anchor_last_day": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date",
                "description": "The UTC day of the last daily integrity anchor; null before the first."
              },
              "evidence_archive": {
                "description": "The newest day of the evidence archive; null before the first.",
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "last_day",
                      "status"
                    ],
                    "properties": {
                      "last_day": {
                        "type": "string",
                        "format": "date"
                      },
                      "status": {
                        "type": "string",
                        "enum": [
                          "building",
                          "archived"
                        ]
                      }
                    }
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "platform_alerts_open": {
                "type": "integer",
                "minimum": 0,
                "description": "The platform's own open alerts (of no company)."
              },
              "platform_alerts_open_high": {
                "type": "integer",
                "minimum": 0,
                "description": "Of them, severity high."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "read_only": false,
          "warnings": [],
          "db": {
            "dialect": "postgresql",
            "schema_version": 108,
            "expected_schema_version": 108,
            "round_trip_ms": 0.8
          },
          "mqtt": {
            "connected": true,
            "subscribed": true
          },
          "certificates": [
            {
              "name": "broker",
              "not_after": "2027-01-02T00:00:00Z",
              "days_left": 77
            }
          ],
          "tsa": {
            "mode": "on",
            "pending": 0,
            "failing": 0
          },
          "issuer_keys": {
            "available": true
          },
          "anchor_last_day": "2026-10-16",
          "evidence_archive": {
            "last_day": "2026-10-15",
            "status": "archived"
          },
          "platform_alerts_open": 0,
          "platform_alerts_open_high": 0
        }
      },
      "PlatformOverviewTraffic": {
        "description": "#274. The requests this server answered since it started (`since`).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "since",
              "answers",
              "server_errors",
              "refused_429",
              "series_since",
              "server_errors_per_minute"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "since": {
                "type": "string",
                "format": "date-time",
                "description": "When this server started counting."
              },
              "answers": {
                "type": "integer",
                "minimum": 0,
                "description": "Every answer."
              },
              "server_errors": {
                "type": "integer",
                "minimum": 0,
                "description": "Answers 500 to 599."
              },
              "refused_429": {
                "type": "integer",
                "minimum": 0,
                "description": "Answers 429 (too many requests)."
              },
              "series_since": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time",
                "description": "When the per-minute series started; null before the first sample."
              },
              "server_errors_per_minute": {
                "type": "array",
                "maxItems": 60,
                "description": "One value per minute, oldest first, at most 60, measured while the overview is opened (from `series_since`); null for a minute that was not measured. Never padded with zeros.",
                "items": {
                  "type": [
                    "integer",
                    "null"
                  ],
                  "minimum": 0
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "since": "2026-10-17T01:02:03Z",
          "answers": 18234,
          "server_errors": 2,
          "refused_429": 14,
          "series_since": "2026-10-17T07:28:05Z",
          "server_errors_per_minute": [
            0,
            0,
            1,
            0
          ]
        }
      },
      "PlatformOverviewIngest": {
        "description": "#274. The device message ingest of this server since it started, the device messages stored per minute (about: a quarantine review or a correction counts too) and the ingest backlog.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "since",
              "outcomes",
              "series_since",
              "messages_per_minute",
              "backlog"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "since": {
                "type": "string",
                "format": "date-time",
                "description": "When this server started counting."
              },
              "outcomes": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "accepted",
                  "quarantined",
                  "duplicate",
                  "rejected"
                ],
                "properties": {
                  "accepted": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "quarantined": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "duplicate": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "rejected": {
                    "type": "integer",
                    "minimum": 0
                  }
                }
              },
              "series_since": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time",
                "description": "When the per-minute series started; null before the first sample."
              },
              "messages_per_minute": {
                "type": "array",
                "maxItems": 60,
                "description": "One value per minute, oldest first, at most 60, measured while the overview is opened (from `series_since`); null for a minute that was not measured. Never padded with zeros.",
                "items": {
                  "type": [
                    "integer",
                    "null"
                  ],
                  "minimum": 0
                }
              },
              "backlog": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "messages",
                  "capped",
                  "companies",
                  "over_budget"
                ],
                "properties": {
                  "messages": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Device messages waiting, at most 1,000,000."
                  },
                  "capped": {
                    "type": "boolean",
                    "description": "More than 1,000,000 wait: `messages` is 1,000,000."
                  },
                  "companies": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Companies with a message waiting."
                  },
                  "over_budget": {
                    "type": [
                      "integer",
                      "null"
                    ],
                    "minimum": 0,
                    "description": "Companies over their backlog disk budget; null on a process without the MQTT bridge (only the bridge's process counts the bytes)."
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "since": "2026-10-17T01:02:03Z",
          "outcomes": {
            "accepted": 90122,
            "quarantined": 12,
            "duplicate": 40,
            "rejected": 3
          },
          "series_since": "2026-10-17T07:28:05Z",
          "messages_per_minute": [
            1502,
            1498,
            1510
          ],
          "backlog": {
            "messages": 0,
            "capped": false,
            "companies": 0,
            "over_budget": 0
          }
        }
      },
      "PlatformOverviewQueues": {
        "description": "#274. The queues the platform works through.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "outbound",
              "webhooks_pending",
              "email",
              "recall_notices_pending",
              "exports"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "outbound": {
                "type": [
                  "object",
                  "null"
                ],
                "additionalProperties": {
                  "type": "integer",
                  "minimum": 0
                },
                "description": "Records waiting to be sent, per partner system; null when the health figures could not be read."
              },
              "webhooks_pending": {
                "type": "integer",
                "minimum": 0,
                "description": "Webhook deliveries waiting."
              },
              "email": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "queued",
                  "oldest_queued_at",
                  "failed_24h"
                ],
                "properties": {
                  "queued": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Emails waiting to be sent."
                  },
                  "oldest_queued_at": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "format": "date-time",
                    "description": "When the oldest of them was queued; null when none waits."
                  },
                  "failed_24h": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Emails that failed within 24 hours."
                  }
                }
              },
              "recall_notices_pending": {
                "type": "integer",
                "minimum": 0,
                "description": "Recall notices not yet delivered."
              },
              "exports": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "active",
                  "failed_7d"
                ],
                "properties": {
                  "active": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Company data exports queued or running."
                  },
                  "failed_7d": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Company data exports failed within 7 days."
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "outbound": {
            "epcis": 0
          },
          "webhooks_pending": 0,
          "email": {
            "queued": 0,
            "oldest_queued_at": null,
            "failed_24h": 0
          },
          "recall_notices_pending": 0,
          "exports": {
            "active": 0,
            "failed_7d": 0
          }
        }
      },
      "PlatformOverviewWaiting": {
        "description": "#274. The work waiting on CropPath.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "device_approvals",
              "gateway_approvals",
              "key_approvals",
              "facility_proposals",
              "boundary_proposals",
              "support_open",
              "support_in_progress",
              "lab_accreditations_expiring",
              "lab_approvals_expiring",
              "companies_leaving"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "device_approvals": {
                "type": "integer",
                "minimum": 0,
                "description": "Devices waiting for approval."
              },
              "gateway_approvals": {
                "type": "integer",
                "minimum": 0,
                "description": "Gateways waiting for approval."
              },
              "key_approvals": {
                "type": "integer",
                "minimum": 0,
                "description": "Active keys waiting for approval."
              },
              "facility_proposals": {
                "type": "integer",
                "minimum": 0,
                "description": "Facilities proposed by a company, not yet approved."
              },
              "boundary_proposals": {
                "type": "integer",
                "minimum": 0,
                "description": "Growing area boundaries proposed, not yet decided."
              },
              "support_open": {
                "type": "integer",
                "minimum": 0,
                "description": "Support requests open."
              },
              "support_in_progress": {
                "type": "integer",
                "minimum": 0,
                "description": "Support requests in progress."
              },
              "lab_accreditations_expiring": {
                "type": "integer",
                "minimum": 0,
                "description": "Active labs whose accreditation ends within 60 days."
              },
              "lab_approvals_expiring": {
                "type": "integer",
                "minimum": 0,
                "description": "Active lab market approvals ending within 60 days and not renewed."
              },
              "companies_leaving": {
                "type": "integer",
                "minimum": 0,
                "description": "Companies leaving CropPath."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "device_approvals": 1,
          "gateway_approvals": 0,
          "key_approvals": 0,
          "facility_proposals": 2,
          "boundary_proposals": 0,
          "support_open": 1,
          "support_in_progress": 0,
          "lab_accreditations_expiring": 0,
          "lab_approvals_expiring": 1,
          "companies_leaving": 0
        }
      },
      "PlatformOverviewSecurity": {
        "description": "#274. Sign-in security.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "failed_sign_ins_24h",
              "capped",
              "accounts_locked"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "failed_sign_ins_24h": {
                "type": "integer",
                "minimum": 0,
                "description": "Failed sign-ins within 24 hours, at most 10,000."
              },
              "capped": {
                "type": "boolean",
                "description": "More than 10,000: `failed_sign_ins_24h` is 10,000."
              },
              "accounts_locked": {
                "type": "integer",
                "minimum": 0,
                "description": "Accounts locked now after failed sign-ins."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "failed_sign_ins_24h": 5,
          "capped": false,
          "accounts_locked": 0
        }
      },
      "PlatformOverviewCompany": {
        "type": "object",
        "description": "#274. One company's figures: its name and code and counts, never a person's data.",
        "additionalProperties": false,
        "required": [
          "id",
          "name",
          "sandbox",
          "offboarding",
          "members_active",
          "admins_active",
          "devices_registered",
          "messages_last_hour",
          "api_calls_today",
          "api_day_percent",
          "open_high_alerts",
          "support_open"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "sandbox": {
            "type": "boolean",
            "description": "A hosted sandbox company."
          },
          "offboarding": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "leaving",
              "left",
              null
            ],
            "description": "Whether the company is leaving or has left CropPath; null otherwise."
          },
          "members_active": {
            "type": "integer",
            "minimum": 0
          },
          "admins_active": {
            "type": "integer",
            "minimum": 0,
            "description": "Active company admins."
          },
          "devices_registered": {
            "type": "integer",
            "minimum": 0,
            "description": "Devices of every status."
          },
          "messages_last_hour": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "description": "Device messages stored in the last hour; null until the server has measured an hour."
          },
          "api_calls_today": {
            "type": "integer",
            "minimum": 0,
            "description": "API calls this UTC day."
          },
          "api_day_percent": {
            "type": "integer",
            "minimum": 0,
            "description": "`api_calls_today` as a percentage of the daily API call quota."
          },
          "open_high_alerts": {
            "type": "integer",
            "minimum": 0,
            "description": "Open alerts of severity high."
          },
          "support_open": {
            "type": "integer",
            "minimum": 0,
            "description": "Support requests open."
          }
        },
        "example": {
          "id": "coop-dl",
          "name": "HTX Dak Lak",
          "sandbox": false,
          "offboarding": null,
          "members_active": 9,
          "admins_active": 2,
          "devices_registered": 42,
          "messages_last_hour": 9000,
          "api_calls_today": 1200,
          "api_day_percent": 0,
          "open_high_alerts": 2,
          "support_open": 1
        }
      },
      "PlatformOverviewCompanies": {
        "description": "#274. The companies: at most 50, those that need attention first (open high alerts, open support requests, the daily API quota at its warning level), then by id.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "total",
              "items"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "total": {
                "type": "integer",
                "minimum": 0,
                "description": "Every company."
              },
              "items": {
                "type": "array",
                "maxItems": 50,
                "items": {
                  "$ref": "#/components/schemas/PlatformOverviewCompany"
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "total": 1,
          "items": [
            {
              "id": "coop-dl",
              "name": "HTX Dak Lak",
              "sandbox": false,
              "offboarding": null,
              "members_active": 9,
              "admins_active": 2,
              "devices_registered": 42,
              "messages_last_hour": 9000,
              "api_calls_today": 1200,
              "api_day_percent": 0,
              "open_high_alerts": 2,
              "support_open": 1
            }
          ]
        }
      },
      "PlatformOverview": {
        "type": "object",
        "description": "#274. The platform overview for platform admins: the service's health, its traffic, the ingest and the queues, the work waiting on CropPath, sign-in security and the companies. The per-minute figures and the traffic are this server's, from when it started (`process.started_at`). Each section has `state`: `ok` with its figures, or `unavailable` (OverviewSectionUnavailable) when it could not be read.",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "max_age_s",
          "process",
          "sections"
        ],
        "properties": {
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it for up to `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "minimum": 0,
            "description": "Seconds the server serves one answer."
          },
          "process": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "started_at",
              "role",
              "mqtt_ingest"
            ],
            "properties": {
              "started_at": {
                "type": "string",
                "format": "date-time",
                "description": "When this server started: its counts restart with it."
              },
              "role": {
                "type": "string",
                "enum": [
                  "all",
                  "public"
                ]
              },
              "mqtt_ingest": {
                "type": "string",
                "enum": [
                  "bridge",
                  "workers",
                  "shared-bridge"
                ],
                "description": "Who stores the device messages: this process's MQTT bridge, or the ingest workers (whose own counts are not in `ingest.outcomes`)."
              }
            }
          },
          "sections": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "health",
              "traffic",
              "ingest",
              "queues",
              "waiting",
              "security",
              "companies"
            ],
            "properties": {
              "health": {
                "$ref": "#/components/schemas/PlatformOverviewHealth"
              },
              "traffic": {
                "$ref": "#/components/schemas/PlatformOverviewTraffic"
              },
              "ingest": {
                "$ref": "#/components/schemas/PlatformOverviewIngest"
              },
              "queues": {
                "$ref": "#/components/schemas/PlatformOverviewQueues"
              },
              "waiting": {
                "$ref": "#/components/schemas/PlatformOverviewWaiting"
              },
              "security": {
                "$ref": "#/components/schemas/PlatformOverviewSecurity"
              },
              "companies": {
                "$ref": "#/components/schemas/PlatformOverviewCompanies"
              },
              "irrigation": {
                "$ref": "#/components/schemas/PlatformOverviewIrrigation"
              }
            }
          }
        },
        "example": {
          "generated_at": "2026-10-17T07:32:05Z",
          "max_age_s": 30,
          "process": {
            "started_at": "2026-10-17T01:02:03Z",
            "role": "all",
            "mqtt_ingest": "bridge"
          },
          "sections": {
            "health": {
              "state": "ok",
              "read_only": false,
              "warnings": [],
              "db": {
                "dialect": "postgresql",
                "schema_version": 108,
                "expected_schema_version": 108,
                "round_trip_ms": 0.8
              },
              "mqtt": {
                "connected": true,
                "subscribed": true
              },
              "certificates": [
                {
                  "name": "broker",
                  "not_after": "2027-01-02T00:00:00Z",
                  "days_left": 77
                }
              ],
              "tsa": {
                "mode": "on",
                "pending": 0,
                "failing": 0
              },
              "issuer_keys": {
                "available": true
              },
              "anchor_last_day": "2026-10-16",
              "evidence_archive": {
                "last_day": "2026-10-15",
                "status": "archived"
              },
              "platform_alerts_open": 0,
              "platform_alerts_open_high": 0
            },
            "traffic": {
              "state": "ok",
              "since": "2026-10-17T01:02:03Z",
              "answers": 18234,
              "server_errors": 2,
              "refused_429": 14,
              "series_since": "2026-10-17T07:28:05Z",
              "server_errors_per_minute": [
                0,
                0,
                1,
                0
              ]
            },
            "ingest": {
              "state": "ok",
              "since": "2026-10-17T01:02:03Z",
              "outcomes": {
                "accepted": 90122,
                "quarantined": 12,
                "duplicate": 40,
                "rejected": 3
              },
              "series_since": "2026-10-17T07:28:05Z",
              "messages_per_minute": [
                1502,
                1498,
                1510
              ],
              "backlog": {
                "messages": 0,
                "capped": false,
                "companies": 0,
                "over_budget": 0
              }
            },
            "queues": {
              "state": "ok",
              "outbound": {
                "epcis": 0
              },
              "webhooks_pending": 0,
              "email": {
                "queued": 0,
                "oldest_queued_at": null,
                "failed_24h": 0
              },
              "recall_notices_pending": 0,
              "exports": {
                "active": 0,
                "failed_7d": 0
              }
            },
            "waiting": {
              "state": "ok",
              "device_approvals": 1,
              "gateway_approvals": 0,
              "key_approvals": 0,
              "facility_proposals": 2,
              "boundary_proposals": 0,
              "support_open": 1,
              "support_in_progress": 0,
              "lab_accreditations_expiring": 0,
              "lab_approvals_expiring": 1,
              "companies_leaving": 0
            },
            "security": {
              "state": "ok",
              "failed_sign_ins_24h": 5,
              "capped": false,
              "accounts_locked": 0
            },
            "companies": {
              "state": "ok",
              "total": 1,
              "items": [
                {
                  "id": "coop-dl",
                  "name": "HTX Dak Lak",
                  "sandbox": false,
                  "offboarding": null,
                  "members_active": 9,
                  "admins_active": 2,
                  "devices_registered": 42,
                  "messages_last_hour": 9000,
                  "api_calls_today": 1200,
                  "api_day_percent": 0,
                  "open_high_alerts": 2,
                  "support_open": 1
                }
              ]
            },
            "irrigation": {
              "state": "ok",
              "controllers": 14,
              "online": 12,
              "not_measured": 1,
              "controllers_capped": false,
              "online_rate_7d": [
                0.98,
                0.97,
                0.99,
                0.99,
                0.96,
                0.98,
                0.99
              ],
              "rejects_14d": {
                "interlock": 1,
                "manual_override_active": 4
              },
              "expired_rate_14d": 0.02,
              "commands_capped": false,
              "companies": [
                {
                  "id": "coop-dl",
                  "open_urgent": 0,
                  "alarms_raised_7d": 18
                }
              ],
              "capped": false,
              "attention": []
            }
          }
        }
      },
      "ConsoleHomeSessions": {
        "description": "#286. The measurement sessions open or paused now, one per busy line, newest first.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "total",
              "items"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "total": {
                "type": "integer",
                "minimum": 0,
                "description": "Sessions open or paused now."
              },
              "items": {
                "type": "array",
                "maxItems": 50,
                "description": "At most 50 of them, the most recently opened first (one per line, so every busy line is listed until a scope has more than 50 busy lines).",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "lot",
                    "variety",
                    "facility",
                    "line",
                    "status",
                    "opened_at",
                    "paused_at",
                    "fruits",
                    "opened_by_you"
                  ],
                  "properties": {
                    "id": {
                      "type": "string",
                      "description": "The session's id."
                    },
                    "lot": {
                      "type": "string",
                      "description": "The lot's code."
                    },
                    "variety": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The lot's variety."
                    },
                    "facility": {
                      "type": "string",
                      "description": "The packing house (facility code)."
                    },
                    "line": {
                      "type": "string"
                    },
                    "status": {
                      "type": "string",
                      "enum": [
                        "open",
                        "paused"
                      ]
                    },
                    "opened_at": {
                      "type": "string",
                      "format": "date-time",
                      "description": "When the session was opened."
                    },
                    "paused_at": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "When the session was last paused; null when it never was."
                    },
                    "fruits": {
                      "type": "integer",
                      "minimum": 0,
                      "description": "Fruits recorded on the lot so far."
                    },
                    "opened_by_you": {
                      "type": "boolean",
                      "description": "Whether the caller opened the session. Who else opened it is not part of the answer."
                    }
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "total": 1,
          "items": [
            {
              "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
              "lot": "LO-260928-014",
              "variety": "Ri6",
              "facility": "VN-TGPH-021",
              "line": "A2",
              "status": "open",
              "opened_at": "2026-10-18T00:42:00Z",
              "paused_at": null,
              "fruits": 128,
              "opened_by_you": true
            }
          ]
        }
      },
      "ConsoleHomeTask": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "count",
          "oldest"
        ],
        "properties": {
          "count": {
            "type": "integer",
            "minimum": 0,
            "description": "Lots of the window that need this action."
          },
          "oldest": {
            "type": "array",
            "maxItems": 5,
            "description": "The 5 oldest of them, oldest first (by the time of the step the action follows; a lot whose step time is unknown comes last).",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "code",
                "facility",
                "since"
              ],
              "properties": {
                "code": {
                  "type": "string",
                  "description": "The lot's code."
                },
                "facility": {
                  "type": "string",
                  "description": "The lot's packing house (facility code)."
                },
                "since": {
                  "type": [
                    "string",
                    "null"
                  ],
                  "format": "date-time",
                  "description": "When the step the action follows happened (see the task); null when unknown."
                }
              }
            }
          }
        }
      },
      "ConsoleHomeWork": {
        "description": "#286. The work by next action, read among the newest 1,000 lots of each packing house in scope (of the company for a company-wide answer). A lot may need several actions.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "window",
              "tasks"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "window": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "per_facility",
                  "full"
                ],
                "properties": {
                  "per_facility": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "How many of the newest lots are read: per packing house, or of the whole company when `scope.all_facilities` is true."
                  },
                  "full": {
                    "type": "boolean",
                    "description": "A packing house (or the company) has that many lots or more: older lots are not counted."
                  }
                }
              },
              "tasks": {
                "type": "object",
                "description": "One entry per action: `measure`: Lots not measured yet (draft), since their creation. `close`: Open lots with no session measuring (a paused session is closed by the close), since their creation. `sample`: Closed or packed lots never sampled, since their close (#283): the lot page's lab sampling card chooses the samples. `lab_failed`: Lots whose lab result failed and that are not shipped, recalled or withdrawn (a shipment refuses them), since the result arrived. `lab_waiting`: Lots waiting for their lab result (samples drawn, no result yet), since the samples were drawn. `pack`: Closed lots to pack and seal, since their close. `label`: Packed lots with no export label printed, since they were packed. `ship`: Packed lots on no shipment, since they were packed. `recalled`: Lots recalled or withdrawn in the last 30 days, since the recall.",
                "additionalProperties": false,
                "required": [
                  "measure",
                  "close",
                  "sample",
                  "lab_failed",
                  "lab_waiting",
                  "pack",
                  "label",
                  "ship",
                  "recalled"
                ],
                "properties": {
                  "measure": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "close": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "sample": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "lab_failed": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "lab_waiting": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "pack": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "label": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "ship": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  },
                  "recalled": {
                    "$ref": "#/components/schemas/ConsoleHomeTask"
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "window": {
            "per_facility": 1000,
            "full": false
          },
          "tasks": {
            "measure": {
              "count": 1,
              "oldest": [
                {
                  "code": "LO-261018-002",
                  "facility": "VN-TGPH-021",
                  "since": "2026-10-18T01:05:00Z"
                }
              ]
            },
            "close": {
              "count": 0,
              "oldest": []
            },
            "sample": {
              "count": 0,
              "oldest": []
            },
            "lab_failed": {
              "count": 0,
              "oldest": []
            },
            "lab_waiting": {
              "count": 1,
              "oldest": [
                {
                  "code": "LO-260927-009",
                  "facility": "VN-TGPH-021",
                  "since": "2026-10-17T09:30:00Z"
                }
              ]
            },
            "pack": {
              "count": 1,
              "oldest": [
                {
                  "code": "LO-260927-011",
                  "facility": "VN-TGPH-021",
                  "since": "2026-10-17T10:20:00Z"
                }
              ]
            },
            "label": {
              "count": 0,
              "oldest": []
            },
            "ship": {
              "count": 1,
              "oldest": [
                {
                  "code": "LO-260926-004",
                  "facility": "VN-TGPH-021",
                  "since": "2026-10-16T08:00:00Z"
                }
              ]
            },
            "recalled": {
              "count": 0,
              "oldest": []
            }
          }
        }
      },
      "ConsoleHomeShipments": {
        "description": "#286. Shipments not departed, oldest first (a shipment has no planned departure); #283: and the shipments departed in the last 30 days whose temperature logger readings are missing or incomplete.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "open",
              "items",
              "logger_missing"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "open": {
                "type": "integer",
                "minimum": 0,
                "description": "Shipments not departed."
              },
              "items": {
                "type": "array",
                "maxItems": 5,
                "description": "The 5 oldest.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "facility",
                    "lots",
                    "logger_check",
                    "created_at"
                  ],
                  "properties": {
                    "code": {
                      "type": "string"
                    },
                    "facility": {
                      "type": "string"
                    },
                    "lots": {
                      "type": "integer",
                      "minimum": 0,
                      "description": "Lots on the shipment."
                    },
                    "logger_check": {
                      "type": "string",
                      "enum": [
                        "missing",
                        "incomplete",
                        "out_of_range",
                        "matched"
                      ],
                      "description": "The temperature logger check of the shipment."
                    },
                    "created_at": {
                      "type": "string",
                      "format": "date-time",
                      "description": "When the shipment was created."
                    }
                  }
                }
              },
              "logger_missing": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "count",
                  "oldest"
                ],
                "description": "#283. Shipments departed in the last 30 days whose temperature logger check is `missing` or `incomplete`: the readings are read out after the trip, and the shipment page's logger card adds them.",
                "properties": {
                  "count": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "oldest": {
                    "type": "array",
                    "maxItems": 5,
                    "description": "The 5 that departed first.",
                    "items": {
                      "type": "object",
                      "additionalProperties": false,
                      "required": [
                        "code",
                        "facility",
                        "logger_check",
                        "since"
                      ],
                      "properties": {
                        "code": {
                          "type": "string"
                        },
                        "facility": {
                          "type": "string"
                        },
                        "logger_check": {
                          "type": "string",
                          "enum": [
                            "missing",
                            "incomplete"
                          ]
                        },
                        "since": {
                          "type": "string",
                          "format": "date-time",
                          "description": "When the shipment departed."
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "open": 1,
          "items": [
            {
              "code": "SH-260930-01",
              "facility": "VN-TGPH-021",
              "lots": 2,
              "logger_check": "missing",
              "created_at": "2026-10-17T08:00:00Z"
            }
          ],
          "logger_missing": {
            "count": 1,
            "oldest": [
              {
                "code": "SH-260925-02",
                "facility": "VN-TGPH-021",
                "logger_check": "missing",
                "since": "2026-10-15T23:00:00Z"
              }
            ]
          }
        }
      },
      "ConsoleHomeReview": {
        "description": "#286. Device messages of the scope waiting for a company admin's review (quarantined); a lot with such messages cannot be closed until they are reviewed.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "quarantined",
              "capped",
              "oldest_received_at"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "quarantined": {
                "type": "integer",
                "minimum": 0,
                "description": "At most 10,000."
              },
              "capped": {
                "type": "boolean",
                "description": "More than 10,000 wait: `quarantined` is 10,000."
              },
              "oldest_received_at": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time",
                "description": "When the oldest waiting message was received; null when none waits."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "quarantined": 0,
          "capped": false,
          "oldest_received_at": null
        }
      },
      "ConsoleHomeDevices": {
        "description": "#286. The active devices and stations (gateways) of the scope's packing houses. A device belongs to a packing house, not to a line.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "total",
              "capped",
              "items",
              "gateways",
              "gateways_capped"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "total": {
                "type": "integer",
                "minimum": 0,
                "description": "Active devices in scope."
              },
              "capped": {
                "type": "boolean",
                "description": "More than 50: `items` lists 50."
              },
              "items": {
                "type": "array",
                "maxItems": 50,
                "description": "By packing house, then device id.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "device_id",
                    "name",
                    "facility",
                    "measures",
                    "approval",
                    "ready",
                    "last_seen",
                    "calibration_valid_until"
                  ],
                  "properties": {
                    "device_id": {
                      "type": "string"
                    },
                    "name": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The device's display name; null without one."
                    },
                    "facility": {
                      "type": "string",
                      "description": "The packing house the device belongs to."
                    },
                    "measures": {
                      "type": "boolean",
                      "description": "Whether the device takes part in measuring (its profile takes the session command); false for temperature loggers and packing stations."
                    },
                    "approval": {
                      "type": "string",
                      "enum": [
                        "pending",
                        "approved",
                        "rejected"
                      ],
                      "description": "CropPath's approval of the device."
                    },
                    "ready": {
                      "type": "boolean",
                      "description": "Whether the device sent a message within 24 hours and holds a key that may sign (as `ready` of the device)."
                    },
                    "last_seen": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "When the device's last message arrived; null when it never sent one."
                    },
                    "calibration_valid_until": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "The end of the device's newest calibration still in effect (not superseded); null when none is recorded."
                    }
                  }
                }
              },
              "gateways": {
                "type": "array",
                "maxItems": 50,
                "description": "The active stations, by packing house.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "gateway_id",
                    "name",
                    "facility",
                    "last_heartbeat",
                    "silent"
                  ],
                  "properties": {
                    "gateway_id": {
                      "type": "string"
                    },
                    "name": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "The station's display name; null without one."
                    },
                    "facility": {
                      "type": "string"
                    },
                    "last_heartbeat": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "format": "date-time",
                      "description": "When the station's last heartbeat arrived; null when never."
                    },
                    "silent": {
                      "type": "boolean",
                      "description": "No heartbeat within 24 hours."
                    }
                  }
                }
              },
              "gateways_capped": {
                "type": "boolean",
                "description": "More than 50 stations: `gateways` lists 50."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "total": 1,
          "capped": false,
          "items": [
            {
              "device_id": "sf100-0417",
              "name": "SF-100",
              "facility": "VN-TGPH-021",
              "measures": true,
              "approval": "approved",
              "ready": true,
              "last_seen": "2026-10-18T02:11:58Z",
              "calibration_valid_until": "2026-11-15T00:00:00Z"
            }
          ],
          "gateways": [
            {
              "gateway_id": "gw-tp-01",
              "name": "Station Tân Phú",
              "facility": "VN-TGPH-021",
              "last_heartbeat": "2026-10-18T02:11:00Z",
              "silent": false
            }
          ],
          "gateways_capped": false
        }
      },
      "ConsoleHomeToday": {
        "description": "#286. Today so far, `day` of the answer (the Vietnam calendar day); lot counts among the newest 1,000 lots of each packing house.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "lots_created",
              "lots_closed",
              "lots_packed",
              "shipments_departed",
              "messages",
              "messages_capped"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "lots_created": {
                "type": "integer",
                "minimum": 0,
                "description": "Lots created today."
              },
              "lots_closed": {
                "type": "integer",
                "minimum": 0,
                "description": "Lots closed and signed today."
              },
              "lots_packed": {
                "type": "integer",
                "minimum": 0,
                "description": "Lots packed today."
              },
              "shipments_departed": {
                "type": "integer",
                "minimum": 0,
                "description": "Shipments departed today."
              },
              "messages": {
                "type": "integer",
                "minimum": 0,
                "description": "Device messages received today, at most 100,000."
              },
              "messages_capped": {
                "type": "boolean",
                "description": "More than 100,000: `messages` is 100,000."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "lots_created": 2,
          "lots_closed": 1,
          "lots_packed": 0,
          "shipments_departed": 0,
          "messages": 5123,
          "messages_capped": false
        }
      },
      "ConsoleHome": {
        "type": "object",
        "description": "#286. The console's work home for the selected company within the caller's packing houses (every packing house of the company for a company admin): what is measuring now, the work by next action, open shipments, messages waiting for review, the devices and stations, and today's counts. Codes and counts of the company only, and the names of its packing houses. Each section has `state`: `ok` with its figures, or `unavailable` (OverviewSectionUnavailable) when it could not be read.",
        "additionalProperties": false,
        "required": [
          "tenant",
          "generated_at",
          "max_age_s",
          "day",
          "scope",
          "sections"
        ],
        "properties": {
          "tenant": {
            "type": "string",
            "description": "The selected company."
          },
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it for up to `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "minimum": 0,
            "description": "Seconds the server serves one answer."
          },
          "day": {
            "type": "object",
            "description": "The day `today` counts in: the Vietnam calendar day (UTC+7).",
            "additionalProperties": false,
            "required": [
              "date",
              "starts_at",
              "time_zone"
            ],
            "properties": {
              "date": {
                "type": "string",
                "format": "date"
              },
              "starts_at": {
                "type": "string",
                "format": "date-time",
                "description": "Its start (00:00 in Vietnam), in UTC."
              },
              "time_zone": {
                "type": "string",
                "enum": [
                  "Asia/Ho_Chi_Minh"
                ]
              }
            }
          },
          "scope": {
            "type": "object",
            "description": "Whose work the answer counts.",
            "additionalProperties": false,
            "required": [
              "all_facilities",
              "facilities"
            ],
            "properties": {
              "all_facilities": {
                "type": "boolean",
                "description": "The whole company (a company admin, a platform admin acting for it, or an operator of every packing house)."
              },
              "facilities": {
                "type": "array",
                "description": "The packing houses in scope, by code.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "code",
                    "name",
                    "lines"
                  ],
                  "properties": {
                    "code": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "lines": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      },
                      "description": "The packing house's lines."
                    }
                  }
                }
              }
            }
          },
          "sections": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "sessions",
              "work",
              "shipments",
              "review",
              "devices",
              "today"
            ],
            "properties": {
              "sessions": {
                "$ref": "#/components/schemas/ConsoleHomeSessions"
              },
              "work": {
                "$ref": "#/components/schemas/ConsoleHomeWork"
              },
              "shipments": {
                "$ref": "#/components/schemas/ConsoleHomeShipments"
              },
              "review": {
                "$ref": "#/components/schemas/ConsoleHomeReview"
              },
              "devices": {
                "$ref": "#/components/schemas/ConsoleHomeDevices"
              },
              "today": {
                "$ref": "#/components/schemas/ConsoleHomeToday"
              }
            }
          }
        },
        "example": {
          "tenant": "coop-dl",
          "generated_at": "2026-10-18T02:12:40Z",
          "max_age_s": 10,
          "day": {
            "date": "2026-10-18",
            "starts_at": "2026-10-17T17:00:00Z",
            "time_zone": "Asia/Ho_Chi_Minh"
          },
          "scope": {
            "all_facilities": false,
            "facilities": [
              {
                "code": "VN-TGPH-021",
                "name": "Tân Phú",
                "lines": [
                  "A1",
                  "A2",
                  "B1"
                ]
              }
            ]
          },
          "sections": {
            "sessions": {
              "state": "ok",
              "total": 1,
              "items": [
                {
                  "id": "3b1f6c2e-8a4d-4f0b-9c7e-2d5a1b8e6f30",
                  "lot": "LO-260928-014",
                  "variety": "Ri6",
                  "facility": "VN-TGPH-021",
                  "line": "A2",
                  "status": "open",
                  "opened_at": "2026-10-18T00:42:00Z",
                  "paused_at": null,
                  "fruits": 128,
                  "opened_by_you": true
                }
              ]
            },
            "work": {
              "state": "ok",
              "window": {
                "per_facility": 1000,
                "full": false
              },
              "tasks": {
                "measure": {
                  "count": 1,
                  "oldest": [
                    {
                      "code": "LO-261018-002",
                      "facility": "VN-TGPH-021",
                      "since": "2026-10-18T01:05:00Z"
                    }
                  ]
                },
                "close": {
                  "count": 0,
                  "oldest": []
                },
                "sample": {
                  "count": 0,
                  "oldest": []
                },
                "lab_failed": {
                  "count": 0,
                  "oldest": []
                },
                "lab_waiting": {
                  "count": 1,
                  "oldest": [
                    {
                      "code": "LO-260927-009",
                      "facility": "VN-TGPH-021",
                      "since": "2026-10-17T09:30:00Z"
                    }
                  ]
                },
                "pack": {
                  "count": 1,
                  "oldest": [
                    {
                      "code": "LO-260927-011",
                      "facility": "VN-TGPH-021",
                      "since": "2026-10-17T10:20:00Z"
                    }
                  ]
                },
                "label": {
                  "count": 0,
                  "oldest": []
                },
                "ship": {
                  "count": 1,
                  "oldest": [
                    {
                      "code": "LO-260926-004",
                      "facility": "VN-TGPH-021",
                      "since": "2026-10-16T08:00:00Z"
                    }
                  ]
                },
                "recalled": {
                  "count": 0,
                  "oldest": []
                }
              }
            },
            "shipments": {
              "state": "ok",
              "open": 1,
              "items": [
                {
                  "code": "SH-260930-01",
                  "facility": "VN-TGPH-021",
                  "lots": 2,
                  "logger_check": "missing",
                  "created_at": "2026-10-17T08:00:00Z"
                }
              ],
              "logger_missing": {
                "count": 0,
                "oldest": []
              }
            },
            "review": {
              "state": "ok",
              "quarantined": 0,
              "capped": false,
              "oldest_received_at": null
            },
            "devices": {
              "state": "ok",
              "total": 1,
              "capped": false,
              "items": [
                {
                  "device_id": "sf100-0417",
                  "name": "SF-100",
                  "facility": "VN-TGPH-021",
                  "measures": true,
                  "approval": "approved",
                  "ready": true,
                  "last_seen": "2026-10-18T02:11:58Z",
                  "calibration_valid_until": "2026-11-15T00:00:00Z"
                }
              ],
              "gateways": [
                {
                  "gateway_id": "gw-tp-01",
                  "name": "Station Tân Phú",
                  "facility": "VN-TGPH-021",
                  "last_heartbeat": "2026-10-18T02:11:00Z",
                  "silent": false
                }
              ],
              "gateways_capped": false
            },
            "today": {
              "state": "ok",
              "lots_created": 2,
              "lots_closed": 1,
              "lots_packed": 0,
              "shipments_departed": 0,
              "messages": 5123,
              "messages_capped": false
            }
          }
        }
      },
      "LabHomeWaiting": {
        "description": "#286. Samplings waiting for the lab's results (no report yet), oldest first.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "count",
              "past_target",
              "items"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "count": {
                "type": "integer",
                "minimum": 0,
                "description": "Samplings waiting."
              },
              "past_target": {
                "type": "integer",
                "minimum": 0,
                "description": "Of them, drawn more than `target_hours` ago."
              },
              "items": {
                "type": "array",
                "maxItems": 10,
                "description": "The 10 oldest.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "lot",
                    "exporter",
                    "sample_count",
                    "analytes",
                    "selected_at"
                  ],
                  "properties": {
                    "id": {
                      "type": "integer",
                      "description": "The sampling's id."
                    },
                    "lot": {
                      "type": "string",
                      "description": "The lot's code."
                    },
                    "exporter": {
                      "type": "string",
                      "description": "The exporting company's name."
                    },
                    "sample_count": {
                      "type": "integer",
                      "minimum": 1
                    },
                    "analytes": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    },
                    "selected_at": {
                      "type": "string",
                      "format": "date-time",
                      "description": "When the samples were drawn."
                    }
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "count": 3,
          "past_target": 1,
          "items": [
            {
              "id": 71,
              "lot": "LO-260927-009",
              "exporter": "HTX Đắk Lắk",
              "sample_count": 3,
              "analytes": [
                "cadmium",
                "auramine_o"
              ],
              "selected_at": "2026-10-16T03:00:00Z"
            }
          ]
        }
      },
      "LabHomePdfMissing": {
        "description": "#286. Reports stored without their PDF original, oldest first.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "count",
              "items"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "count": {
                "type": "integer",
                "minimum": 0,
                "description": "Reports without their PDF original."
              },
              "items": {
                "type": "array",
                "maxItems": 5,
                "description": "The 5 oldest.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "report_no",
                    "received_at"
                  ],
                  "properties": {
                    "id": {
                      "type": "integer",
                      "description": "The sampling's id."
                    },
                    "report_no": {
                      "type": "string"
                    },
                    "received_at": {
                      "type": "string",
                      "format": "date-time",
                      "description": "When the report was stored."
                    }
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "count": 1,
          "items": [
            {
              "id": 68,
              "report_no": "KN-261015-0031",
              "received_at": "2026-10-15T08:40:00Z"
            }
          ]
        }
      },
      "LabHomeSent": {
        "description": "#286. Reports stored in the last 7 days, newest first.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "count_7d",
              "failed_7d",
              "items"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "count_7d": {
                "type": "integer",
                "minimum": 0,
                "description": "Reports stored in the last 7 days."
              },
              "failed_7d": {
                "type": "integer",
                "minimum": 0,
                "description": "Of them, reports that failed (a failure stops the exporter's shipment)."
              },
              "items": {
                "type": "array",
                "maxItems": 5,
                "description": "The 5 newest.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "lot",
                    "report_no",
                    "passed",
                    "received_at"
                  ],
                  "properties": {
                    "id": {
                      "type": "integer",
                      "description": "The sampling's id."
                    },
                    "lot": {
                      "type": "string",
                      "description": "The lot's code."
                    },
                    "report_no": {
                      "type": "string"
                    },
                    "passed": {
                      "type": "boolean"
                    },
                    "received_at": {
                      "type": "string",
                      "format": "date-time",
                      "description": "When the report was stored."
                    }
                  }
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "count_7d": 4,
          "failed_7d": 0,
          "items": [
            {
              "id": 69,
              "lot": "LO-260925-004",
              "report_no": "KN-261016-0040",
              "passed": true,
              "received_at": "2026-10-16T07:10:00Z"
            }
          ]
        }
      },
      "LabHome": {
        "type": "object",
        "description": "#286. The lab portal's home for the caller's lab: whether the lab can sign (its status, accreditation, market approvals and keys) and its work, read among its newest 500 samplings: samplings waiting for results, reports whose PDF original was not sent, and reports sent in the last 7 days. No person's name. Each section has `state`: `ok` with its figures, or `unavailable` (OverviewSectionUnavailable) when it could not be read.",
        "additionalProperties": false,
        "required": [
          "lab",
          "generated_at",
          "max_age_s",
          "window",
          "target_hours",
          "sections"
        ],
        "properties": {
          "lab": {
            "type": "object",
            "description": "The caller's lab.",
            "additionalProperties": false,
            "required": [
              "code",
              "name",
              "status",
              "accreditation",
              "valid_to",
              "approvals",
              "keys"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "status": {
                "type": "string",
                "enum": [
                  "active",
                  "suspended"
                ],
                "description": "A suspended lab cannot store reports."
              },
              "accreditation": {
                "type": "string"
              },
              "valid_to": {
                "type": "string",
                "format": "date",
                "description": "The last day of the accreditation's validity."
              },
              "approvals": {
                "type": "array",
                "description": "Per market, the approval that ends last (withdrawn approvals left out); an ended one is listed with its end.",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "market",
                    "status",
                    "valid_to"
                  ],
                  "properties": {
                    "market": {
                      "type": "string",
                      "minLength": 2,
                      "maxLength": 2
                    },
                    "status": {
                      "type": "string",
                      "enum": [
                        "active"
                      ]
                    },
                    "valid_to": {
                      "type": "string",
                      "format": "date",
                      "description": "The approval's last valid day."
                    }
                  }
                }
              },
              "keys": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "lab_held",
                  "server_held"
                ],
                "properties": {
                  "lab_held": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Active keys the lab holds itself (to sign uploaded reports)."
                  },
                  "server_held": {
                    "type": "boolean",
                    "description": "Whether the lab has the server-held key that results entered on the portal are signed with."
                  }
                }
              }
            }
          },
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it for up to `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "minimum": 0,
            "description": "Seconds the server serves one answer."
          },
          "window": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "samplings",
              "full"
            ],
            "properties": {
              "samplings": {
                "type": "integer",
                "minimum": 1,
                "description": "How many of the lab's newest samplings are read."
              },
              "full": {
                "type": "boolean",
                "description": "The lab has more samplings: older ones are not counted."
              }
            }
          },
          "target_hours": {
            "type": "integer",
            "minimum": 1,
            "description": "The time from the draw to the results the lab aims for; `waiting.past_target` counts the samplings past it."
          },
          "sections": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "waiting",
              "pdf_missing",
              "sent"
            ],
            "properties": {
              "waiting": {
                "$ref": "#/components/schemas/LabHomeWaiting"
              },
              "pdf_missing": {
                "$ref": "#/components/schemas/LabHomePdfMissing"
              },
              "sent": {
                "$ref": "#/components/schemas/LabHomeSent"
              }
            }
          }
        },
        "example": {
          "lab": {
            "code": "LAB-VN-118",
            "name": "Phòng kiểm nghiệm 118",
            "status": "active",
            "accreditation": "VILAS 118",
            "valid_to": "2027-03-31",
            "approvals": [
              {
                "market": "CN",
                "status": "active",
                "valid_to": "2027-12-31"
              }
            ],
            "keys": {
              "lab_held": 1,
              "server_held": true
            }
          },
          "generated_at": "2026-10-18T02:12:40Z",
          "max_age_s": 30,
          "window": {
            "samplings": 500,
            "full": false
          },
          "target_hours": 48,
          "sections": {
            "waiting": {
              "state": "ok",
              "count": 3,
              "past_target": 1,
              "items": [
                {
                  "id": 71,
                  "lot": "LO-260927-009",
                  "exporter": "HTX Đắk Lắk",
                  "sample_count": 3,
                  "analytes": [
                    "cadmium",
                    "auramine_o"
                  ],
                  "selected_at": "2026-10-16T03:00:00Z"
                }
              ]
            },
            "pdf_missing": {
              "state": "ok",
              "count": 1,
              "items": [
                {
                  "id": 68,
                  "report_no": "KN-261015-0031",
                  "received_at": "2026-10-15T08:40:00Z"
                }
              ]
            },
            "sent": {
              "state": "ok",
              "count_7d": 4,
              "failed_7d": 0,
              "items": [
                {
                  "id": 69,
                  "lot": "LO-260925-004",
                  "report_no": "KN-261016-0040",
                  "passed": true,
                  "received_at": "2026-10-16T07:10:00Z"
                }
              ]
            }
          }
        }
      },
      "PublicCommuneMap": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "url",
          "osm_relation"
        ],
        "description": "#293: the commune map of the record's growing area: one SVG image of the commune the record already names in words (its OpenStreetMap boundary on map tiles CropPath renders itself), never the orchard. Precision is the commune: no orchard point or boundary, no packing house. Present only when exactly one commune of the OpenStreetMap commune dataset in force matches the area's commune (by the official name of its commune code when it has one, else by its registered name; among several communes of that name, the one that holds the area's approved boundary, else the one that holds more than half of its judged positions) and a tile dataset is imported; otherwise the member is null. The image carries the attribution \"© OpenMapTiles © OpenStreetMap contributors\", and a page showing it must show the same text near it, linked to https://openmaptiles.org/ and https://www.openstreetmap.org/copyright.",
        "properties": {
          "url": {
            "$ref": "#/components/schemas/PublicSameOriginPath",
            "description": "The image's same-origin path, `/v1/public/maps/{style}/{tileset}/{communes}/{osm_id}.svg` (GET /v1/public/maps/{style}/{tileset}/{communes}/{osm_id}.svg). It names the drawing's version, the tile dataset, the commune dataset and the commune's OpenStreetMap relation only: never the growing area, its code or a GLN."
          },
          "osm_relation": {
            "type": "integer",
            "minimum": 1,
            "maximum": 999999999999,
            "description": "The commune's OpenStreetMap relation id: https://www.openstreetmap.org/relation/{osm_relation} is its page on OpenStreetMap."
          }
        },
        "x-not-in-sdk": true
      },
      "LabInvitationCreate": {
        "type": "object",
        "required": [
          "email"
        ],
        "additionalProperties": false,
        "properties": {
          "email": {
            "type": "string",
            "maxLength": 320,
            "description": "The lab analyst's email: their sign-in name, not checked by any email."
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200,
            "description": "Proposed as the new account's name; the invitee may change it."
          }
        },
        "example": {
          "email": "analyst@lab-vn-118.example",
          "display_name": "Chi Hoa"
        }
      },
      "LabLogins": {
        "type": "object",
        "required": [
          "members",
          "invitations"
        ],
        "additionalProperties": false,
        "description": "Who signs in for a lab, and its pending invitations. Never a link or its token.",
        "properties": {
          "members": {
            "type": "array",
            "maxItems": 500,
            "description": "Each person with a lab membership for this lab, in any company record, by email (at most 500). `active` when one of those memberships and the account are active, else `disabled` (turned off by CropPath support).",
            "items": {
              "type": "object",
              "required": [
                "email",
                "display_name",
                "status",
                "since"
              ],
              "additionalProperties": false,
              "properties": {
                "email": {
                  "type": "string"
                },
                "display_name": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "status": {
                  "type": "string",
                  "enum": [
                    "active",
                    "disabled"
                  ]
                },
                "since": {
                  "type": [
                    "number",
                    "null"
                  ],
                  "description": "Unix seconds the membership was made; null for one made before memberships recorded it."
                }
              }
            }
          },
          "invitations": {
            "type": "array",
            "maxItems": 50,
            "description": "The lab's invitations still pending (unused, unrevoked, unexpired), newest first.",
            "items": {
              "type": "object",
              "required": [
                "id",
                "email",
                "display_name",
                "created_at",
                "created_by",
                "expires_at"
              ],
              "additionalProperties": false,
              "properties": {
                "id": {
                  "type": "integer",
                  "description": "The link id (for revokeLabInvitation)."
                },
                "email": {
                  "type": "string"
                },
                "display_name": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "created_at": {
                  "type": "number"
                },
                "created_by": {
                  "type": "string",
                  "description": "The platform admin who made it."
                },
                "expires_at": {
                  "type": "number"
                }
              }
            }
          }
        }
      },
      "FacilityCertification": {
        "type": "object",
        "required": [
          "id",
          "facility",
          "scheme",
          "number",
          "issuer",
          "valid_from",
          "valid_to",
          "evidence_sha256",
          "created_at",
          "ended_on",
          "end_reason",
          "ended_at",
          "status"
        ],
        "additionalProperties": false,
        "description": "#269: a packing-house certification of a facility. Shown to the company's staff only: no trust tier and no public page uses them (architect decision on #269; ADR 0001).",
        "properties": {
          "id": {
            "type": "integer"
          },
          "facility": {
            "type": "string"
          },
          "scheme": {
            "type": "string",
            "enum": [
              "ISO 22000",
              "FSSC 22000",
              "BRCGS",
              "IFS"
            ],
            "description": "The packing-house certification scheme, compared exactly."
          },
          "number": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "The certificate number."
          },
          "issuer": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "The certifier (certification body) that issued the certificate."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The first valid day."
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The last valid day, not before valid_from."
          },
          "evidence_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "The SHA-256 of the certificate document, a company upload (GET /v1/attachments/{sha256} for the facility's readers; never public)."
          },
          "created_at": {
            "type": "number",
            "description": "When it was recorded (Unix seconds)."
          },
          "ended_on": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The day it stopped being in force (withdrawn, suspended or replaced), from valid_from to valid_to; null while it was not ended."
          },
          "end_reason": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 500,
            "description": "Why it was ended; null while not."
          },
          "ended_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When it was ended (Unix seconds); null while not."
          },
          "status": {
            "type": "string",
            "enum": [
              "valid",
              "expired",
              "not_yet_valid",
              "ended"
            ],
            "description": "On today's date in Viet Nam: `ended` from ended_on, else `not_yet_valid` before valid_from, `expired` after valid_to, `valid` otherwise."
          }
        },
        "example": {
          "id": 12,
          "facility": "VN-TGPH-021",
          "scheme": "BRCGS",
          "number": "BRC-12345",
          "issuer": "Bureau Veritas Certification",
          "valid_from": "2026-03-01",
          "valid_to": "2027-02-28",
          "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
          "created_at": 1790000000.5,
          "ended_on": null,
          "end_reason": null,
          "ended_at": null,
          "status": "valid"
        }
      },
      "FacilityCertificationList": {
        "type": "object",
        "required": [
          "items"
        ],
        "additionalProperties": false,
        "description": "#269: every certification of a facility (at most 100), newest valid_from first.",
        "properties": {
          "items": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/FacilityCertification"
            }
          }
        },
        "example": {
          "items": [
            {
              "id": 12,
              "facility": "VN-TGPH-021",
              "scheme": "BRCGS",
              "number": "BRC-12345",
              "issuer": "Bureau Veritas Certification",
              "valid_from": "2026-03-01",
              "valid_to": "2027-02-28",
              "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f",
              "created_at": 1790000000.5,
              "ended_on": null,
              "end_reason": null,
              "ended_at": null,
              "status": "valid"
            }
          ]
        }
      },
      "FacilityCertificationCreate": {
        "type": "object",
        "required": [
          "scheme",
          "number",
          "issuer",
          "valid_from",
          "valid_to",
          "evidence_sha256"
        ],
        "additionalProperties": false,
        "description": "#269: a packing-house certification to record on a facility.",
        "properties": {
          "scheme": {
            "type": "string",
            "enum": [
              "ISO 22000",
              "FSSC 22000",
              "BRCGS",
              "IFS"
            ],
            "description": "The packing-house certification scheme, compared exactly."
          },
          "number": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "The certificate number."
          },
          "issuer": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "The certifier."
          },
          "valid_from": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "Not before valid_from."
          },
          "evidence_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "The SHA-256 of the certificate document the company uploaded first with PUT /v1/attachments/{sha256}."
          }
        },
        "example": {
          "scheme": "BRCGS",
          "number": "BRC-12345",
          "issuer": "Bureau Veritas Certification",
          "valid_from": "2026-03-01",
          "valid_to": "2027-02-28",
          "evidence_sha256": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f"
        }
      },
      "FacilityCertificationEnd": {
        "type": "object",
        "required": [
          "ended_on",
          "reason"
        ],
        "additionalProperties": false,
        "description": "#269: the end of a facility's certification.",
        "properties": {
          "ended_on": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The day it stopped being in force, from valid_from to valid_to."
          },
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Why it was ended."
          }
        },
        "example": {
          "ended_on": "2026-10-19",
          "reason": "Suspended by the certification body"
        }
      },
      "Agronomist": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "user_id",
          "email",
          "legal_name",
          "organisation",
          "qualification",
          "contact",
          "note",
          "status",
          "created_at",
          "updated_at",
          "verified_by",
          "verified_at",
          "suspended_by",
          "suspended_at",
          "suspend_reason"
        ],
        "description": "#351: a row of the platform's agronomist registry (control/agronomists.py). Personal data: a platform admin reads every row, the person their own; never on a public read.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "user_id": {
            "type": "integer",
            "description": "The account."
          },
          "email": {
            "type": "string"
          },
          "legal_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "The name a signature names (snapshotted into each attestation)."
          },
          "organisation": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "qualification": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 500
          },
          "contact": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "note": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 500
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "verified",
              "suspended"
            ],
            "description": "`pending` until a platform admin verified the person outside the platform; only a `verified` agronomist signs; `suspended` signs nothing."
          },
          "created_at": {
            "type": "number"
          },
          "updated_at": {
            "type": "number"
          },
          "verified_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "verified_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "suspended_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "suspended_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "suspend_reason": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "example": {
          "id": 3,
          "user_id": 41,
          "email": "agronomist@coop.example",
          "legal_name": "Nguyễn Văn An",
          "organisation": "Viện Khoa học Kỹ thuật Nông nghiệp miền Nam",
          "qualification": "Kỹ sư nông học",
          "contact": "agronomist@coop.example",
          "note": null,
          "status": "verified",
          "created_at": 1790000000.5,
          "updated_at": 1790003600.5,
          "verified_by": "support@croppath.example",
          "verified_at": 1790003600.5,
          "suspended_by": null,
          "suspended_at": null,
          "suspend_reason": null
        }
      },
      "AgronomistPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_before"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Agronomist"
            }
          },
          "next_before": {
            "type": [
              "integer",
              "null"
            ],
            "description": "Pass as `before` for the next page."
          }
        }
      },
      "AgronomistCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "email",
          "legal_name",
          "organisation"
        ],
        "properties": {
          "email": {
            "type": "string",
            "description": "The account's email (the account must exist)."
          },
          "legal_name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "organisation": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "qualification": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 500
          },
          "contact": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 200
          },
          "note": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 500
          }
        }
      },
      "AgronomistVerify": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "note": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 500
          }
        }
      },
      "AgronomistSuspend": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500
          }
        }
      },
      "AgronomyStage": {
        "type": "object",
        "additionalProperties": false,
        "description": "#351: a crop stage. Every member is optional in a draft; signing needs code, name, start and end, and a value given in one stage given in every stage.",
        "properties": {
          "code": {
            "type": "string",
            "pattern": "^[a-z0-9_-]{1,32}$"
          },
          "name": {
            "$ref": "#/components/schemas/AgronomyLocalizedText"
          },
          "start": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "end": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "kc": {
            "type": "number",
            "minimum": 0,
            "maximum": 2,
            "description": "Crop coefficient. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "p_depletion": {
            "type": "number",
            "minimum": 0,
            "maximum": 1,
            "description": "FAO-56 depletion fraction p. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "root_depth_m": {
            "type": "number",
            "minimum": 0.05,
            "maximum": 5,
            "description": "Effective root depth, metres. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "schedule_mm_per_day": {
            "type": "number",
            "minimum": 0,
            "maximum": 20,
            "description": "Scheduled irrigation depth, mm per day. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "moisture_lower_pct": {
            "type": "number",
            "minimum": 0,
            "maximum": 100,
            "description": "Soil moisture band, lower edge (%), below the upper. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "moisture_upper_pct": {
            "type": "number",
            "minimum": 0,
            "maximum": 100,
            "description": "Soil moisture band, upper edge (%). Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "moisture_basis": {
            "type": "object",
            "additionalProperties": false,
            "description": "What the band is read on.",
            "properties": {
              "probe_profile": {
                "type": "string",
                "minLength": 1,
                "maxLength": 64
              },
              "depth_cm": {
                "type": "number",
                "minimum": 0,
                "maximum": 1000
              }
            }
          }
        }
      },
      "AgronomyLocalizedText": {
        "type": "object",
        "additionalProperties": false,
        "description": "#351: a text in each language of the console (all three are needed to sign).",
        "properties": {
          "vi": {
            "type": "string",
            "minLength": 1
          },
          "en": {
            "type": "string",
            "minLength": 1
          },
          "zh-Hans": {
            "type": "string",
            "minLength": 1
          }
        }
      },
      "AgronomyStressWindow": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "start": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "end": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "action": {
            "type": "string",
            "enum": [
              "no_irrigation",
              "cap_fraction",
              "max_mm_per_day"
            ]
          },
          "fraction": {
            "type": "number",
            "minimum": 0,
            "maximum": 1,
            "description": "With `cap_fraction`: the share of the scheduled depth kept. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "max_mm_per_day": {
            "type": "number",
            "minimum": 0,
            "maximum": 20,
            "description": "With `max_mm_per_day`: the cap, mm per day. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "note": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500
          }
        }
      },
      "AgronomySalinity": {
        "type": "object",
        "additionalProperties": false,
        "description": "#351: electrical conductivity in mS/cm only. A member named `g_per_l` (anywhere in the body) is refused: g/L is never used or converted.",
        "properties": {
          "water_ec_limit_ms_cm": {
            "type": "number",
            "minimum": 0,
            "maximum": 200,
            "description": "Irrigation water EC limit, mS/cm. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "soil_ec_limit_ms_cm": {
            "type": "number",
            "minimum": 0,
            "maximum": 100,
            "description": "Soil EC limit, mS/cm. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "soil_ec_basis": {
            "type": "string",
            "enum": [
              "bulk",
              "pore"
            ]
          },
          "action": {
            "type": "string",
            "enum": [
              "block",
              "alert"
            ]
          }
        }
      },
      "AgronomyEt0": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "krs": {
            "type": "number",
            "minimum": 0.1,
            "maximum": 0.25,
            "description": "FAO-56 eq. 50 adjustment coefficient. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "effective_rain_fraction": {
            "type": "number",
            "minimum": 0,
            "maximum": 1,
            "description": "Share of the rain counted as effective. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          }
        }
      },
      "AgronomyPhotoperiod": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "start": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "end": {
            "type": "string",
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "night_start_local": {
            "type": "string",
            "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$"
          },
          "duration_h": {
            "type": "number",
            "minimum": 0,
            "maximum": 14,
            "description": "Lamp hours a night. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          },
          "min_confirmed_h": {
            "type": "number",
            "minimum": 0,
            "maximum": 14,
            "description": "Confirmed hours needed, at most the duration. Sanity bounds only: the value is the agronomist's, never a CropPath default."
          }
        }
      },
      "AgronomyAdvisory": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "text": {
            "$ref": "#/components/schemas/AgronomyLocalizedText"
          },
          "attachment_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "requires_lab_test": {
            "type": "boolean",
            "const": true
          }
        },
        "description": "#351: advice in words only: no digit (amounts and formulas come from a lab test)."
      },
      "AgronomySheetBody": {
        "type": "object",
        "additionalProperties": false,
        "description": "#351: the `agritrace.agronomy-sheet/1` body (control/sheets.py). Every value is optional in a draft and none has a default: CropPath ships no agronomic number.",
        "properties": {
          "stages": {
            "type": "array",
            "maxItems": 24,
            "items": {
              "$ref": "#/components/schemas/AgronomyStage"
            }
          },
          "stress_windows": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/AgronomyStressWindow"
            }
          },
          "salinity": {
            "$ref": "#/components/schemas/AgronomySalinity"
          },
          "et0": {
            "$ref": "#/components/schemas/AgronomyEt0"
          },
          "lighting": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "photoperiod": {
                "type": "array",
                "maxItems": 24,
                "items": {
                  "$ref": "#/components/schemas/AgronomyPhotoperiod"
                }
              }
            }
          },
          "advisory": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "lime": {
                "$ref": "#/components/schemas/AgronomyAdvisory"
              },
              "fertiliser": {
                "$ref": "#/components/schemas/AgronomyAdvisory"
              }
            }
          },
          "references": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "properties": {
                "title": {
                  "type": "string",
                  "minLength": 1,
                  "maxLength": 200
                },
                "url": {
                  "type": "string",
                  "maxLength": 2000
                },
                "sha256": {
                  "type": "string",
                  "pattern": "^[0-9a-f]{64}$"
                }
              }
            }
          }
        }
      },
      "AgronomySheetAttestation": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "agronomist_id",
          "user_id",
          "legal_name",
          "organisation",
          "statement_version",
          "statement_text_sha256",
          "body_sha256",
          "signed_at",
          "second_factor_at"
        ],
        "description": "#351: a signature (append-only): who signed (snapshots of the registry row), the statement agreed to and the hash signed. An in-app attestation recorded by CropPath, not a detached digital signature (ADR 0014).",
        "properties": {
          "id": {
            "type": "integer"
          },
          "agronomist_id": {
            "type": "integer"
          },
          "user_id": {
            "type": "integer"
          },
          "legal_name": {
            "type": "string"
          },
          "organisation": {
            "type": "string"
          },
          "statement_version": {
            "type": "string"
          },
          "statement_text_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "body_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "signed_at": {
            "type": "number"
          },
          "second_factor_at": {
            "type": "number",
            "description": "When the session last proved a second factor."
          }
        }
      },
      "AgronomySheet": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "series_key",
          "crop",
          "variety",
          "province_code",
          "version",
          "status",
          "valid_from",
          "valid_to",
          "body_sha256",
          "created_by",
          "created_at",
          "updated_by",
          "updated_at",
          "copied_from_id",
          "supersedes_id",
          "superseded_by_id",
          "signed_at",
          "superseded_at",
          "revoked_at",
          "revoked_by",
          "revoke_reason",
          "body",
          "attestation"
        ],
        "description": "#351: an agronomic input sheet of the company (control/sheets.py).",
        "properties": {
          "id": {
            "type": "integer"
          },
          "series_key": {
            "type": "string",
            "description": "`<crop>:<variety>:<province>`; `*` for every variety or province."
          },
          "crop": {
            "type": "string",
            "description": "A code of the crop registry."
          },
          "variety": {
            "type": "string"
          },
          "province_code": {
            "type": "string",
            "pattern": "^([0-9]{2}|\\*)$"
          },
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "status": {
            "type": "string",
            "enum": [
              "draft",
              "signed",
              "superseded",
              "revoked"
            ]
          },
          "valid_from": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "body_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "The SHA-256 of the sheet's JCS document (GET .../document): what a signature covers."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "updated_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "updated_at": {
            "type": "number"
          },
          "copied_from_id": {
            "type": [
              "integer",
              "null"
            ]
          },
          "supersedes_id": {
            "type": [
              "integer",
              "null"
            ]
          },
          "superseded_by_id": {
            "type": [
              "integer",
              "null"
            ]
          },
          "signed_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "superseded_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoked_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "revoke_reason": {
            "type": [
              "string",
              "null"
            ]
          },
          "body": {
            "$ref": "#/components/schemas/AgronomySheetBody"
          },
          "attestation": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/AgronomySheetAttestation"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      },
      "AgronomySheetSummary": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "series_key",
          "crop",
          "variety",
          "province_code",
          "version",
          "status",
          "valid_from",
          "valid_to",
          "body_sha256",
          "created_at",
          "updated_at",
          "signed_at",
          "superseded_at",
          "revoked_at",
          "signed_by"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "series_key": {
            "type": "string",
            "description": "`<crop>:<variety>:<province>`; `*` for every variety or province."
          },
          "crop": {
            "type": "string",
            "description": "A code of the crop registry."
          },
          "variety": {
            "type": "string"
          },
          "province_code": {
            "type": "string",
            "pattern": "^([0-9]{2}|\\*)$"
          },
          "version": {
            "type": "integer",
            "minimum": 1
          },
          "status": {
            "type": "string",
            "enum": [
              "draft",
              "signed",
              "superseded",
              "revoked"
            ]
          },
          "valid_from": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "body_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$",
            "description": "The SHA-256 of the sheet's JCS document (GET .../document): what a signature covers."
          },
          "created_at": {
            "type": "number"
          },
          "updated_at": {
            "type": "number"
          },
          "signed_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "superseded_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "revoked_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "signed_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "The signer's legal name."
          }
        }
      },
      "AgronomySheetPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_before"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AgronomySheetSummary"
            }
          },
          "next_before": {
            "type": [
              "integer",
              "null"
            ]
          }
        }
      },
      "AgronomySheetCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "crop"
        ],
        "properties": {
          "crop": {
            "type": "string",
            "pattern": "^[a-z][a-z0-9_]{0,63}$"
          },
          "variety": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "`*` (the default) for every variety; no `:`."
          },
          "province_code": {
            "type": "string",
            "pattern": "^([0-9]{2}|\\*)$",
            "description": "`*` (the default) for every province."
          },
          "valid_from": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "body": {
            "$ref": "#/components/schemas/AgronomySheetBody"
          }
        }
      },
      "AgronomySheetUpdate": {
        "type": "object",
        "additionalProperties": false,
        "description": "Each member given replaces the draft's; one left out stays.",
        "properties": {
          "valid_from": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": [
              "string",
              "null"
            ],
            "format": "date",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "body": {
            "$ref": "#/components/schemas/AgronomySheetBody"
          }
        }
      },
      "AgronomySheetDocument": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "spec",
          "document",
          "sha256",
          "statement"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "spec": {
            "type": "string",
            "const": "agritrace.agronomy-sheet/1"
          },
          "document": {
            "type": "string",
            "description": "The RFC 8785 (JCS) text of {spec, tenant, series_key, version, valid_from, valid_to, body}: hash its UTF-8 bytes to check `sha256`."
          },
          "sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "statement": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "version",
              "text",
              "sha256"
            ],
            "properties": {
              "version": {
                "type": "string"
              },
              "text": {
                "$ref": "#/components/schemas/AgronomyLocalizedText"
              },
              "sha256": {
                "type": "string",
                "pattern": "^[0-9a-f]{64}$",
                "description": "The SHA-256 of the JCS form of the texts."
              }
            }
          }
        }
      },
      "AgronomySheetSign": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "body_sha256",
          "statement_version"
        ],
        "properties": {
          "body_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "statement_version": {
            "type": "string"
          }
        }
      },
      "AgronomySheetRevoke": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500
          }
        }
      },
      "AgronomyHome": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "now",
          "today",
          "status"
        ],
        "description": "#351: the agronomist's home in the selected company.",
        "properties": {
          "generated_at": {
            "type": "number"
          },
          "now": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "drafts_waiting",
              "drafts"
            ],
            "description": "The drafts waiting for a signature, oldest first (at most 20).",
            "properties": {
              "drafts_waiting": {
                "type": "integer"
              },
              "drafts": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/AgronomySheetSummary"
                }
              }
            }
          },
          "today": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "reason",
              "programs",
              "fallback_zones"
            ],
            "description": "#352: today's control work resting on sheets the caller signed: the programs composed for today that cite one (newest first, at most 20) and the rules bound to one whose zones are on their fallback schedule.",
            "properties": {
              "state": {
                "type": "string",
                "enum": [
                  "not_available",
                  "available"
                ]
              },
              "reason": {
                "type": "string"
              },
              "programs": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/AgronomyTodayProgram"
                }
              },
              "fallback_zones": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/AgronomyFallbackRule"
                }
              }
            }
          },
          "status": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "registry",
              "two_factor",
              "expiring_days",
              "expiring",
              "step_up",
              "can_sign"
            ],
            "properties": {
              "registry": {
                "type": [
                  "string",
                  "null"
                ],
                "enum": [
                  "pending",
                  "verified",
                  "suspended",
                  null
                ],
                "description": "The caller's registry status; null without a row."
              },
              "two_factor": {
                "type": "boolean"
              },
              "expiring_days": {
                "type": "integer"
              },
              "expiring": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/AgronomySheetSummary"
                },
                "description": "The caller's signed sheets whose last valid day is within `expiring_days`, soonest first."
              },
              "step_up": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "fresh",
                  "until"
                ],
                "properties": {
                  "fresh": {
                    "type": "boolean"
                  },
                  "until": {
                    "type": [
                      "number",
                      "null"
                    ]
                  }
                }
              },
              "can_sign": {
                "type": "boolean",
                "description": "Verified and two-step sign-in on (the step-up is asked at signing)."
              }
            }
          }
        }
      },
      "ControlZone": {
        "type": "object",
        "additionalProperties": false,
        "description": "#352: an irrigation zone of a controller, with its installation facts (control/zones.py).",
        "required": [
          "id",
          "device_id",
          "zone",
          "growing_area",
          "name",
          "irrigated_area_m2",
          "nominal_flow_lpm",
          "efficiency",
          "max_daily_l",
          "probes",
          "weather_station",
          "controller_utc_offset",
          "offset_ok",
          "field_capacity_pct",
          "wilting_point_pct",
          "created_by",
          "created_at",
          "updated_by",
          "updated_at"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "device_id": {
            "type": "string"
          },
          "zone": {
            "type": "integer",
            "minimum": 1,
            "maximum": 16
          },
          "growing_area": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "irrigated_area_m2": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "nominal_flow_lpm": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "efficiency": {
            "type": "number",
            "minimum": 0.3,
            "maximum": 1
          },
          "max_daily_l": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "probes": {
            "type": "array",
            "maxItems": 16,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "device_id",
                "depth_cm"
              ],
              "properties": {
                "device_id": {
                  "type": "string"
                },
                "depth_cm": {
                  "type": "number",
                  "minimum": 0,
                  "maximum": 1000
                }
              }
            },
            "description": "The soil moisture probes that watch the zone: devices of the company whose profile produces soil.moisture (#365)."
          },
          "weather_station": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "device_id",
              "wind_height_m",
              "elevation_m"
            ],
            "properties": {
              "device_id": {
                "type": "string"
              },
              "wind_height_m": {
                "type": "number",
                "minimum": 0.5,
                "maximum": 20
              },
              "elevation_m": {
                "type": "number",
                "minimum": -500,
                "maximum": 9000
              }
            }
          },
          "controller_utc_offset": {
            "type": "string",
            "pattern": "^[+-](0[0-9]|1[0-4]):[0-5][0-9]$"
          },
          "field_capacity_pct": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "maximum": 100,
            "description": "#353: the zone soil's volumetric water content at field capacity (%), a measurement of the site, never a default; given with wilting_point_pct (above it) or not at all. The et0_budget rule's root-zone bucket needs both."
          },
          "wilting_point_pct": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 100,
            "description": "#353: the zone soil's volumetric water content at the permanent wilting point (%), below field_capacity_pct; given with it or not at all."
          },
          "offset_ok": {
            "type": "boolean",
            "description": "Whether the controller is on Viet Nam time (+07:00): a zone that is not blocks the rules watering it."
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "updated_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "updated_at": {
            "type": "number"
          }
        }
      },
      "ControlZoneCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "device_id",
          "zone",
          "name",
          "irrigated_area_m2",
          "nominal_flow_lpm",
          "efficiency",
          "max_daily_l",
          "controller_utc_offset"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "zone": {
            "type": "integer",
            "minimum": 1,
            "maximum": 16
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "irrigated_area_m2": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "nominal_flow_lpm": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "efficiency": {
            "type": "number",
            "minimum": 0.3,
            "maximum": 1
          },
          "max_daily_l": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "probes": {
            "type": "array",
            "maxItems": 16,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "device_id",
                "depth_cm"
              ],
              "properties": {
                "device_id": {
                  "type": "string"
                },
                "depth_cm": {
                  "type": "number",
                  "minimum": 0,
                  "maximum": 1000
                }
              }
            }
          },
          "weather_station": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "device_id",
              "wind_height_m",
              "elevation_m"
            ],
            "properties": {
              "device_id": {
                "type": "string"
              },
              "wind_height_m": {
                "type": "number",
                "minimum": 0.5,
                "maximum": 20
              },
              "elevation_m": {
                "type": "number",
                "minimum": -500,
                "maximum": 9000
              }
            }
          },
          "controller_utc_offset": {
            "type": "string",
            "pattern": "^[+-](0[0-9]|1[0-4]):[0-5][0-9]$"
          },
          "field_capacity_pct": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "maximum": 100,
            "description": "#353: the zone soil's volumetric water content at field capacity (%), a measurement of the site, never a default; given with wilting_point_pct (above it) or not at all. The et0_budget rule's root-zone bucket needs both."
          },
          "wilting_point_pct": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 100,
            "description": "#353: the zone soil's volumetric water content at the permanent wilting point (%), below field_capacity_pct; given with it or not at all."
          }
        }
      },
      "ControlZoneUpdate": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "irrigated_area_m2": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "nominal_flow_lpm": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "efficiency": {
            "type": "number",
            "minimum": 0.3,
            "maximum": 1
          },
          "max_daily_l": {
            "type": "number",
            "exclusiveMinimum": 0
          },
          "probes": {
            "type": "array",
            "maxItems": 16,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "device_id",
                "depth_cm"
              ],
              "properties": {
                "device_id": {
                  "type": "string"
                },
                "depth_cm": {
                  "type": "number",
                  "minimum": 0,
                  "maximum": 1000
                }
              }
            }
          },
          "weather_station": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "device_id",
              "wind_height_m",
              "elevation_m"
            ],
            "properties": {
              "device_id": {
                "type": "string"
              },
              "wind_height_m": {
                "type": "number",
                "minimum": 0.5,
                "maximum": 20
              },
              "elevation_m": {
                "type": "number",
                "minimum": -500,
                "maximum": 9000
              }
            }
          },
          "controller_utc_offset": {
            "type": "string",
            "pattern": "^[+-](0[0-9]|1[0-4]):[0-5][0-9]$"
          },
          "field_capacity_pct": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "maximum": 100,
            "description": "#353: the zone soil's volumetric water content at field capacity (%), a measurement of the site, never a default; given with wilting_point_pct (above it) or not at all. The et0_budget rule's root-zone bucket needs both."
          },
          "wilting_point_pct": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 100,
            "description": "#353: the zone soil's volumetric water content at the permanent wilting point (%), below field_capacity_pct; given with it or not at all."
          }
        }
      },
      "ControlZonePage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ControlZone"
            }
          }
        }
      },
      "ControlRule": {
        "type": "object",
        "additionalProperties": false,
        "description": "#352: an irrigation rule (control/rules.py): its kind, controller and zones, the exact signed sheet it reads, its windows, approval and the state the engine last left it in.",
        "required": [
          "id",
          "kind",
          "name",
          "device_id",
          "zones",
          "sheet_id",
          "windows",
          "fallback_rule_id",
          "approval",
          "eval_interval_s",
          "min_interval_s",
          "peer_tolerance_pct",
          "min_probes",
          "enabled",
          "state",
          "state_reason",
          "state_at",
          "next_run_at",
          "last_run_at",
          "created_by",
          "created_at",
          "updated_by",
          "updated_at",
          "enabled_by",
          "enabled_at",
          "auto_approval_by",
          "auto_approval_at",
          "sheet",
          "resumed_command_id",
          "hold_until",
          "sheet_gate"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "kind": {
            "type": "string",
            "enum": [
              "schedule",
              "threshold",
              "et0_budget",
              "lighting"
            ],
            "description": "schedule (the stage's daily depth), threshold (soil moisture against the stage's band, falling back to a schedule rule) or et0_budget (#353: Kc x yesterday's ET0 of the zones' weather station less the rain that counts, falling back to a schedule rule); lighting is recorded but never enabled."
          },
          "device_id": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "zones": {
            "type": "array",
            "minItems": 1,
            "maxItems": 16,
            "items": {
              "type": "integer",
              "minimum": 1,
              "maximum": 16
            }
          },
          "sheet_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "A signed agronomic input sheet of the company."
          },
          "windows": {
            "type": "array",
            "minItems": 1,
            "maxItems": 8,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "start_local",
                "max_duration_s"
              ],
              "properties": {
                "start_local": {
                  "type": "string",
                  "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$"
                },
                "max_duration_s": {
                  "type": "integer",
                  "minimum": 60,
                  "maximum": 86400
                }
              }
            }
          },
          "fallback_rule_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "A threshold or et0_budget rule's fallback (required to enable one): a disabled schedule rule of the same controller and zones."
          },
          "eval_interval_s": {
            "type": "integer",
            "minimum": 900,
            "maximum": 86400
          },
          "min_interval_s": {
            "type": "integer",
            "minimum": 300,
            "maximum": 86400
          },
          "peer_tolerance_pct": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "maximum": 100,
            "description": "The health gate's peer tolerance (percentage points): required by a threshold rule; an et0_budget rule takes it with min_probes or neither (with them its probes trim the depth and measure the bucket)."
          },
          "min_probes": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 16,
            "description": "The health gate's minimum of usable probes: required by a threshold rule; an et0_budget rule takes it with peer_tolerance_pct or neither."
          },
          "approval": {
            "type": "string",
            "enum": [
              "required",
              "auto"
            ]
          },
          "enabled": {
            "type": "boolean"
          },
          "state": {
            "type": "string",
            "enum": [
              "disabled",
              "ok",
              "blocked",
              "fallback"
            ]
          },
          "state_reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "Why blocked or on fallback, e.g. `no_signed_sheet`, `sheet_expired`, `sheet_hash_mismatch`, `frozen`, `stale`, `disagreeing`, `fallback_sheet_revoked`, `manual_override` (a person's own program is in force on the controller), `salinity_block` (#354: a zone's EC reading above its sheet's limit with the action `block`)."
          },
          "state_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "next_run_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "last_run_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "created_by": {
            "type": "string"
          },
          "created_at": {
            "type": "number"
          },
          "updated_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "updated_at": {
            "type": "number"
          },
          "enabled_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "enabled_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "auto_approval_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "auto_approval_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "hold_until": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "#367: the end of the hold on the rule's controller (RFC 3339 UTC): until then the engine proposes and sends nothing automatic for it (a withdrawal holds it until the next farm-local midnight). Null when the controller is not held or its hold has ended."
          },
          "sheet": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "id",
              "series_key",
              "version",
              "status",
              "body_sha256",
              "valid_from",
              "valid_to"
            ],
            "properties": {
              "id": {
                "type": "integer"
              },
              "series_key": {
                "type": "string"
              },
              "version": {
                "type": "integer"
              },
              "status": {
                "type": "string",
                "enum": [
                  "draft",
                  "signed",
                  "superseded",
                  "revoked"
                ]
              },
              "body_sha256": {
                "type": "string"
              },
              "valid_from": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "valid_to": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          },
          "sheet_gate": {
            "type": [
              "string",
              "null"
            ],
            "description": "#354: the reason the rule's sheet would block it today (the sheet gate the engine runs on every compose, on today's local date): `no_signed_sheet`, `sheet_superseded`, `sheet_revoked`, `sheet_hash_mismatch`, `sheet_not_started`, `sheet_expired`, `signer_not_verified`, `sheet_crop_mismatch` or `sheet_incomplete`; null when the sheet is usable."
          },
          "resumed_command_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The person's own set_program an admin resumed the controller's rules over (POST .../resume), or null."
          }
        }
      },
      "ControlRuleCreate": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "kind",
          "name",
          "device_id",
          "zones",
          "windows"
        ],
        "properties": {
          "kind": {
            "type": "string",
            "enum": [
              "schedule",
              "threshold",
              "et0_budget",
              "lighting"
            ],
            "description": "schedule (the stage's daily depth), threshold (soil moisture against the stage's band, falling back to a schedule rule) or et0_budget (#353: Kc x yesterday's ET0 of the zones' weather station less the rain that counts, falling back to a schedule rule); lighting is recorded but never enabled."
          },
          "device_id": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "zones": {
            "type": "array",
            "minItems": 1,
            "maxItems": 16,
            "items": {
              "type": "integer",
              "minimum": 1,
              "maximum": 16
            }
          },
          "sheet_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "A signed agronomic input sheet of the company."
          },
          "windows": {
            "type": "array",
            "minItems": 1,
            "maxItems": 8,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "start_local",
                "max_duration_s"
              ],
              "properties": {
                "start_local": {
                  "type": "string",
                  "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$"
                },
                "max_duration_s": {
                  "type": "integer",
                  "minimum": 60,
                  "maximum": 86400
                }
              }
            }
          },
          "fallback_rule_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "A threshold or et0_budget rule's fallback (required to enable one): a disabled schedule rule of the same controller and zones."
          },
          "eval_interval_s": {
            "type": "integer",
            "minimum": 900,
            "maximum": 86400
          },
          "min_interval_s": {
            "type": "integer",
            "minimum": 300,
            "maximum": 86400
          },
          "peer_tolerance_pct": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "maximum": 100,
            "description": "The health gate's peer tolerance (percentage points): required by a threshold rule; an et0_budget rule takes it with min_probes or neither (with them its probes trim the depth and measure the bucket)."
          },
          "min_probes": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 16,
            "description": "The health gate's minimum of usable probes: required by a threshold rule; an et0_budget rule takes it with peer_tolerance_pct or neither."
          }
        }
      },
      "ControlRuleUpdate": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "zones": {
            "type": "array",
            "minItems": 1,
            "maxItems": 16,
            "items": {
              "type": "integer",
              "minimum": 1,
              "maximum": 16
            }
          },
          "sheet_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "A signed agronomic input sheet of the company."
          },
          "windows": {
            "type": "array",
            "minItems": 1,
            "maxItems": 8,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "start_local",
                "max_duration_s"
              ],
              "properties": {
                "start_local": {
                  "type": "string",
                  "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$"
                },
                "max_duration_s": {
                  "type": "integer",
                  "minimum": 60,
                  "maximum": 86400
                }
              }
            }
          },
          "fallback_rule_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "A threshold or et0_budget rule's fallback (required to enable one): a disabled schedule rule of the same controller and zones."
          },
          "eval_interval_s": {
            "type": "integer",
            "minimum": 900,
            "maximum": 86400
          },
          "min_interval_s": {
            "type": "integer",
            "minimum": 300,
            "maximum": 86400
          },
          "peer_tolerance_pct": {
            "type": [
              "number",
              "null"
            ],
            "exclusiveMinimum": 0,
            "maximum": 100,
            "description": "The health gate's peer tolerance (percentage points): required by a threshold rule; an et0_budget rule takes it with min_probes or neither (with them its probes trim the depth and measure the bucket)."
          },
          "min_probes": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 1,
            "maximum": 16,
            "description": "The health gate's minimum of usable probes: required by a threshold rule; an et0_budget rule takes it with peer_tolerance_pct or neither."
          }
        }
      },
      "ControlRuleApproval": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "approval"
        ],
        "properties": {
          "approval": {
            "type": "string",
            "enum": [
              "required",
              "auto"
            ]
          }
        }
      },
      "ControlRulePage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_before"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ControlRule"
            }
          },
          "next_before": {
            "type": [
              "integer",
              "null"
            ]
          }
        }
      },
      "ControlProgramStep": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "zone",
          "start_s",
          "duration_s",
          "max_volume_l"
        ],
        "properties": {
          "zone": {
            "type": "integer",
            "minimum": 1,
            "maximum": 16
          },
          "start_s": {
            "type": "integer",
            "minimum": 0,
            "maximum": 86399
          },
          "duration_s": {
            "type": "integer",
            "minimum": 1,
            "maximum": 3600
          },
          "max_volume_l": {
            "type": "number",
            "minimum": 1,
            "maximum": 20000
          }
        }
      },
      "ControlProgramSummary": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "device_id",
          "local_date",
          "status",
          "cause",
          "proposed_at",
          "expires_at",
          "decided_by",
          "decided_at",
          "dispatched_at",
          "command_id",
          "program_version",
          "error",
          "steps",
          "litres",
          "rules",
          "sheets",
          "withdrew"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "device_id": {
            "type": "string"
          },
          "local_date": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "proposed",
              "approved",
              "rejected",
              "dispatched",
              "superseded",
              "failed",
              "blocked",
              "expired",
              "withdrawn"
            ]
          },
          "cause": {
            "type": "string",
            "enum": [
              "daily",
              "threshold",
              "recompose"
            ]
          },
          "proposed_at": {
            "type": "number"
          },
          "expires_at": {
            "type": "number"
          },
          "decided_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "decided_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "dispatched_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "command_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "program_version": {
            "type": [
              "integer",
              "null"
            ]
          },
          "error": {
            "type": [
              "string",
              "null"
            ]
          },
          "steps": {
            "type": "integer"
          },
          "litres": {
            "type": "number"
          },
          "rules": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "kind",
                "state",
                "applied"
              ],
              "properties": {
                "id": {
                  "type": [
                    "integer",
                    "null"
                  ]
                },
                "kind": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "state": {
                  "type": "string"
                },
                "applied": {
                  "type": "string"
                }
              }
            }
          },
          "sheets": {
            "type": "array",
            "description": "Every sheet the program cites: its id, version, series and SHA-256.",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "version",
                "series_key",
                "body_sha256"
              ],
              "properties": {
                "id": {
                  "type": "integer"
                },
                "version": {
                  "type": "integer"
                },
                "series_key": {
                  "type": "string"
                },
                "body_sha256": {
                  "type": "string"
                }
              }
            }
          },
          "withdrew": {
            "type": "boolean",
            "description": "The controller's earlier program was withdrawn with this row."
          }
        }
      },
      "ControlProgramPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_before"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ControlProgramSummary"
            }
          },
          "next_before": {
            "type": [
              "integer",
              "null"
            ]
          }
        }
      },
      "ControlGateDecision": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "zone",
          "rule_id",
          "decided_at",
          "verdict",
          "reason",
          "detail"
        ],
        "properties": {
          "zone": {
            "type": "integer"
          },
          "rule_id": {
            "type": "integer"
          },
          "decided_at": {
            "type": "number"
          },
          "verdict": {
            "type": "string",
            "enum": [
              "healthy",
              "fallback",
              "blocked"
            ]
          },
          "reason": {
            "type": [
              "string",
              "null"
            ]
          },
          "detail": {
            "type": "object",
            "description": "Every probe's reading and status, the basis and the peer check (control/health_gate.py)."
          }
        }
      },
      "ControlProgram": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "device_id",
          "local_date",
          "status",
          "cause",
          "proposed_at",
          "expires_at",
          "decided_by",
          "decided_at",
          "dispatched_at",
          "command_id",
          "program_version",
          "error",
          "steps",
          "litres",
          "rules",
          "sheets",
          "withdrew",
          "params",
          "provenance",
          "decision_note",
          "withdrawal",
          "gate_decisions",
          "command"
        ],
        "description": "#352: a program the engine composed (control/programs.py), with the #242 command it became.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "device_id": {
            "type": "string"
          },
          "local_date": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "proposed",
              "approved",
              "rejected",
              "dispatched",
              "superseded",
              "failed",
              "blocked",
              "expired",
              "withdrawn"
            ]
          },
          "cause": {
            "type": "string",
            "enum": [
              "daily",
              "threshold",
              "recompose"
            ]
          },
          "proposed_at": {
            "type": "number"
          },
          "expires_at": {
            "type": "number"
          },
          "decided_by": {
            "type": [
              "string",
              "null"
            ]
          },
          "decided_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "dispatched_at": {
            "type": [
              "number",
              "null"
            ]
          },
          "command_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "program_version": {
            "type": [
              "integer",
              "null"
            ]
          },
          "error": {
            "type": [
              "string",
              "null"
            ]
          },
          "steps": {
            "type": "integer"
          },
          "litres": {
            "type": "number"
          },
          "rules": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "kind",
                "state",
                "applied"
              ],
              "properties": {
                "id": {
                  "type": [
                    "integer",
                    "null"
                  ]
                },
                "kind": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "state": {
                  "type": "string"
                },
                "applied": {
                  "type": "string"
                }
              }
            }
          },
          "sheets": {
            "type": "array",
            "description": "Every sheet the program cites: its id, version, series and SHA-256.",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "version",
                "series_key",
                "body_sha256"
              ],
              "properties": {
                "id": {
                  "type": "integer"
                },
                "version": {
                  "type": "integer"
                },
                "series_key": {
                  "type": "string"
                },
                "body_sha256": {
                  "type": "string"
                }
              }
            }
          },
          "withdrew": {
            "type": "boolean",
            "description": "The controller's earlier program was withdrawn with this row."
          },
          "params": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "program"
            ],
            "description": "The set_program params: as sent once dispatched (with the program_version CropPath assigned), else as they would be sent now.",
            "properties": {
              "program": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "steps"
                ],
                "properties": {
                  "steps": {
                    "type": "array",
                    "maxItems": 48,
                    "items": {
                      "$ref": "#/components/schemas/ControlProgramStep"
                    }
                  }
                }
              },
              "program_version": {
                "type": "integer",
                "minimum": 1,
                "maximum": 2147483647
              },
              "valid_until_s": {
                "type": "integer",
                "minimum": 60,
                "maximum": 86400
              }
            }
          },
          "provenance": {
            "type": "object",
            "description": "What composed it: the rules and how each applied, every sheet cited (id, version, SHA-256, attestation id), each zone's decision, budget and clamps, the day's placed steps (`plan`), per zone the planned depth and litres with their clamps and an ET0 zone's trace (`budget`, #353), the weather stations' ET0 days cited (`et0`, #353) and the decisions' signature (control/engine.py). A zone's record may carry `salinity` (#354, control/salinity.py) when its sheet has a salinity section: {state ok|exceeded|not_measured, action block|alert, water {limit_ms_cm, state, sources[]}, soil {limit_ms_cm, basis bulk|pore, capability, state, sources[]}, stale_s}, electrical conductivity in mS/cm only. An exceedance with the action `block` gives the zone no steps (mode `blocked`, reason `salinity_block`), blocks its rule (`salinity_block`) and raises a high alert `salinity_block`; with the action `alert` the zone is watered as decided and a warning alert `salinity_alert` is raised. `not_measured` never starts a block. A zone a fallback waters is checked against the salinity sections of both sheets, the fallback rule's and its own rule's (the strictest applies); its record then also carries `salinity_sheets` [{sheet_id, evaluation}], the sheet watering it first, while `salinity` is the binding evaluation. A zone blocked by salinity in today's reference program, or named by an open `salinity_block` alert of the controller, stays blocked while its `block` section reads `not_measured` (reason `salinity_block`, the record's `held` `not_measured`), until a usable reading at or below the limit is found. The salinity alerts' detail lists every zone a compose found (`zones` [{zone, rule_id, sheet_id, action, exceeded}]); a new one is raised when such a zone is in no open alert of its kind, and a person resolves them."
          },
          "decision_note": {
            "type": [
              "string",
              "null"
            ]
          },
          "withdrawal": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "by",
              "at",
              "reason"
            ],
            "description": "#367: who withdrew the program from the controller (null to an agronomist), when (RFC 3339 UTC) and why (`[removed]` once the company has left); null unless its status is `withdrawn`.",
            "properties": {
              "by": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "at": {
                "type": "string",
                "format": "date-time"
              },
              "reason": {
                "type": "string",
                "minLength": 1,
                "maxLength": 500
              }
            }
          },
          "gate_decisions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ControlGateDecision"
            }
          },
          "command": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "id",
              "status",
              "reason",
              "issued_by",
              "issued_at",
              "accepted_at",
              "completed_at",
              "expires_at",
              "result",
              "replies"
            ],
            "properties": {
              "id": {
                "type": "string"
              },
              "status": {
                "type": "string"
              },
              "reason": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "issued_by": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Who issued the command; null to an agronomist."
              },
              "issued_at": {
                "type": "number"
              },
              "accepted_at": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "completed_at": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "expires_at": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "result": {
                "type": [
                  "object",
                  "null"
                ]
              },
              "replies": {
                "type": "array",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "received_at",
                    "applied",
                    "body"
                  ],
                  "properties": {
                    "received_at": {
                      "type": "number"
                    },
                    "applied": {
                      "type": "boolean"
                    },
                    "body": {
                      "description": "The reply as received; null to an agronomist."
                    }
                  }
                }
              }
            }
          }
        }
      },
      "ControlProgramReject": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500
          }
        }
      },
      "ControlPreview": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "rule_id",
          "device_id",
          "provenance",
          "gate",
          "params",
          "blocked_zones"
        ],
        "description": "#352: a dry run of a rule's controller as if the rule were enabled; nothing written or sent.",
        "properties": {
          "generated_at": {
            "type": "number"
          },
          "rule_id": {
            "type": "integer"
          },
          "device_id": {
            "type": "string"
          },
          "provenance": {
            "type": "object",
            "description": "As a program's provenance. A zone's record may carry `salinity` (#354, control/salinity.py) when its sheet has a salinity section: {state ok|exceeded|not_measured, action block|alert, water {limit_ms_cm, state, sources[]}, soil {limit_ms_cm, basis bulk|pore, capability, state, sources[]}, stale_s}, electrical conductivity in mS/cm only. An exceedance with the action `block` gives the zone no steps (mode `blocked`, reason `salinity_block`), blocks its rule (`salinity_block`) and raises a high alert `salinity_block`; with the action `alert` the zone is watered as decided and a warning alert `salinity_alert` is raised. `not_measured` never starts a block. A zone a fallback waters is checked against the salinity sections of both sheets, the fallback rule's and its own rule's (the strictest applies); its record then also carries `salinity_sheets` [{sheet_id, evaluation}], the sheet watering it first, while `salinity` is the binding evaluation. A zone blocked by salinity in today's reference program, or named by an open `salinity_block` alert of the controller, stays blocked while its `block` section reads `not_measured` (reason `salinity_block`, the record's `held` `not_measured`), until a usable reading at or below the limit is found. The salinity alerts' detail lists every zone a compose found (`zones` [{zone, rule_id, sheet_id, action, exceeded}]); a new one is raised when such a zone is in no open alert of its kind, and a person resolves them."
          },
          "gate": {
            "type": "array",
            "items": {
              "type": "object"
            }
          },
          "params": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "program"
            ],
            "description": "The set_program params: as sent once dispatched (with the program_version CropPath assigned), else as they would be sent now.",
            "properties": {
              "program": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "steps"
                ],
                "properties": {
                  "steps": {
                    "type": "array",
                    "maxItems": 48,
                    "items": {
                      "$ref": "#/components/schemas/ControlProgramStep"
                    }
                  }
                }
              },
              "program_version": {
                "type": "integer",
                "minimum": 1,
                "maximum": 2147483647
              },
              "valid_until_s": {
                "type": "integer",
                "minimum": 60,
                "maximum": 86400
              }
            }
          },
          "blocked_zones": {
            "type": "array",
            "items": {
              "type": "integer"
            }
          }
        }
      },
      "ControlEt0Day": {
        "type": "object",
        "additionalProperties": false,
        "description": "#353: the latest stored version (`seq`) of the reference ET0 (FAO-56 Penman-Monteith, meteorology only: no sheet value) of a weather station's local day (control/et0_inputs.py, `et0_daily`). A compose appends a version only when the latest was refused or needed the krs and the day now reads differently, a capability's coverage grew, or a plausibility verdict arrived; programs cite the version they used.",
        "required": [
          "device_id",
          "local_date",
          "seq",
          "wind_height_m",
          "elevation_m",
          "status",
          "reason",
          "et0_mm",
          "inputs",
          "trace",
          "computed_at",
          "estimated"
        ],
        "properties": {
          "device_id": {
            "type": "string",
            "description": "The weather station."
          },
          "local_date": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "The local day (Asia/Ho_Chi_Minh, midnight to midnight)."
          },
          "seq": {
            "type": "integer",
            "minimum": 1,
            "description": "The version of the station day (1, 2, ...): the latest is listed."
          },
          "wind_height_m": {
            "type": "number",
            "minimum": 0.5,
            "maximum": 20,
            "description": "The anemometer's height the zone gives (eq. 47)."
          },
          "elevation_m": {
            "type": "number",
            "minimum": -500,
            "maximum": 9000,
            "description": "The station's elevation the zone gives (eqs. 7 and 37)."
          },
          "status": {
            "type": "string",
            "enum": [
              "ok",
              "needs_krs",
              "refused"
            ],
            "description": "`ok` with `et0_mm`; `needs_krs`: no usable measured radiation (a daylight hour without a reading, none at all, a suspect sun or night-light check, or a measured Rs above 1.05 x the clear-sky Rso: a sensor fault), each rule estimates it by eq. 50 with its own sheet's krs (the program's provenance has that ET0); `refused`: no ET0 (`reason`), the rule falls back."
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "Why not `ok`: station_not_approved, station_not_placed, temperature_coverage, out_of_range (refused); radiation_coverage, no_radiation, light_suspect, radiation_above_clear_sky (needs_krs)."
          },
          "et0_mm": {
            "type": [
              "number",
              "null"
            ],
            "minimum": 0,
            "maximum": 15,
            "description": "mm/day; null unless ok."
          },
          "inputs": {
            "type": "object",
            "description": "The daily inputs and how each was found: latitude_deg (the placement's), day_of_year, g (0, eq. 42), coverage (per capability: readings, coverage_h of the 24 local hours, truncated), rain {mm, method, estimated}, tmax and tmin (degC), ea {value kPa, method dew_point|rh_max_min|rh_mean|tdew_tmin, estimated}, u2 {value m/s, method measured|default_2_m_s, estimated}, pressure {value kPa, method measured|elevation}, rs {value MJ m-2 day-1 or null, method measured|eq50_krs, estimated}. Also `longitude_deg`, `daylight_hours` (the local hours with the sun up at their midpoint: Rs is the sum of their hourly means x 0.0036, the night counting 0), `light_verdicts` (the plausibility job's sun and night-light verdicts read), and on `pressure` a `measured_rejected` value when the measured pressure was more than 10 % from eq. 7's."
          },
          "trace": {
            "type": "object",
            "additionalProperties": {
              "type": "number"
            },
            "description": "Every intermediate of the equations (tmean, pressure_kpa, gamma, delta, es, ea, vpd, ra, rs, rso, rns, rnl, rn, g, u2, et0_mm) and hargreaves_mm, the paper's cross-check only (eq. 52). `methods_diverge`: Hargreaves more than 25 % from Penman-Monteith (an alert, no change of water); `rs_clamped_to_rso` on an eq. 50 estimate."
          },
          "computed_at": {
            "type": "number"
          },
          "estimated": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "ea",
                "u2",
                "rs",
                "rain"
              ]
            },
            "description": "The inputs that are estimated."
          }
        }
      },
      "ControlEt0Page": {
        "type": "object",
        "additionalProperties": false,
        "description": "#353: the stored ET0 days of a span of local dates, by station and date (at most 2000).",
        "required": [
          "from",
          "to",
          "items",
          "truncated"
        ],
        "properties": {
          "from": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "to": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ControlEt0Day"
            }
          },
          "truncated": {
            "type": "boolean",
            "description": "A cap was reached (the items, or one of the reads behind them: zones, program rows, step runs): the answer is not whole."
          }
        }
      },
      "ControlBudgetDay": {
        "type": "object",
        "additionalProperties": false,
        "description": "#353: a zone's water on a local date: what the program in force of the day planned for it (the engine's `holding` rule over a day, control/in_force.py, shared with the zone history) and what the controller reported delivered (control/budget.py). A refused or failed command never reads as planned water. Null where the source holds nothing, never a filled-in 0.",
        "required": [
          "device_id",
          "zone",
          "name",
          "growing_area",
          "local_date",
          "plan",
          "program_id",
          "rule_id",
          "mode",
          "planned_mm",
          "planned_l",
          "clamps",
          "et0",
          "applied_l",
          "applied_mm"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "zone": {
            "type": "integer",
            "minimum": 1,
            "maximum": 16
          },
          "name": {
            "type": "string"
          },
          "growing_area": {
            "type": "string"
          },
          "local_date": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "plan": {
            "type": "string",
            "enum": [
              "dispatched",
              "withdrawn",
              "replaced",
              "refused",
              "none",
              "proposed",
              "approved",
              "rejected",
              "superseded",
              "failed",
              "blocked",
              "expired"
            ],
            "description": "`dispatched` (the engine's program the controller held that day), `withdrawn` (the controller no longer ran it: a later row of the day recorded its withdrawal, a person withdrew it, a withdrawal of the controller's program was asked for after its dispatch, or the controller reported it replaced or cancelled, #367 cross-review M1), `replaced` (a person's own set_program replaced it: no planned water), `refused` (every program of the day that became a command was refused or failed: no planned water), else the status of the day's latest program, or `none`."
          },
          "program_id": {
            "type": [
              "integer",
              "null"
            ]
          },
          "rule_id": {
            "type": [
              "integer",
              "null"
            ]
          },
          "mode": {
            "type": [
              "string",
              "null"
            ]
          },
          "planned_mm": {
            "type": [
              "number",
              "null"
            ],
            "description": "`planned_l` over the zone's irrigated area (1 L/m2 = 1 mm), the water given, before efficiency, the zone history's basis; null without a plan. The depth at the roots stays in the program's provenance and `et0`."
          },
          "planned_l": {
            "type": [
              "number",
              "null"
            ],
            "description": "The planned litres of the program in force; null without one."
          },
          "clamps": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "et0": {
            "type": [
              "object",
              "null"
            ],
            "description": "An et0_budget zone's trace: the station day, its ET0 and krs, the estimated inputs, Kc and its stage, the rain and its effective fraction, ETc, the net depth, the trim and the bucket."
          },
          "applied_l": {
            "type": [
              "number",
              "null"
            ],
            "description": "The litres the controller reported; null when it reported nothing."
          },
          "applied_mm": {
            "type": [
              "number",
              "null"
            ],
            "description": "`applied_l` over the zone's irrigated area, the basis of `planned_mm`."
          }
        }
      },
      "ControlBudgetPage": {
        "type": "object",
        "additionalProperties": false,
        "description": "#353: planned and applied water per zone and local date (at most 2000 items).",
        "required": [
          "from",
          "to",
          "items",
          "truncated"
        ],
        "properties": {
          "from": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "to": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ControlBudgetDay"
            }
          },
          "truncated": {
            "type": "boolean",
            "description": "A cap was reached (the items, or one of the reads behind them: zones, program rows, step runs): the answer is not whole."
          }
        }
      },
      "ControlHome": {
        "type": "object",
        "additionalProperties": false,
        "description": "#354: the irrigation control home (control/home.py): what needs a person today, for the controllers in scope.",
        "required": [
          "generated_at",
          "controllers",
          "programs_waiting",
          "rules",
          "salinity",
          "et0"
        ],
        "properties": {
          "generated_at": {
            "type": "number"
          },
          "controllers": {
            "type": "integer",
            "minimum": 0,
            "description": "The company's controllers with a control zone in scope."
          },
          "programs_waiting": {
            "type": "object",
            "additionalProperties": false,
            "description": "The programs still `proposed` (waiting for a person's approval): their count and the newest 5.",
            "required": [
              "count",
              "items"
            ],
            "properties": {
              "count": {
                "type": "integer",
                "minimum": 0
              },
              "items": {
                "type": "array",
                "maxItems": 5,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "device_id",
                    "local_date",
                    "proposed_at"
                  ],
                  "properties": {
                    "id": {
                      "type": "integer"
                    },
                    "device_id": {
                      "type": "string"
                    },
                    "local_date": {
                      "type": "string",
                      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
                    },
                    "proposed_at": {
                      "type": "number"
                    }
                  }
                }
              }
            }
          },
          "rules": {
            "type": "object",
            "additionalProperties": false,
            "description": "The company's rules in scope by what they need.",
            "required": [
              "total",
              "ok",
              "blocked",
              "fallback",
              "not_ready",
              "items"
            ],
            "properties": {
              "total": {
                "type": "integer",
                "minimum": 0
              },
              "ok": {
                "type": "integer",
                "minimum": 0,
                "description": "Enabled rules the engine left `ok`."
              },
              "blocked": {
                "type": "integer",
                "minimum": 0,
                "description": "Enabled rules the engine left `blocked`."
              },
              "fallback": {
                "type": "integer",
                "minimum": 0,
                "description": "Enabled rules the engine left on their fallback schedule."
              },
              "not_ready": {
                "type": "integer",
                "minimum": 0,
                "description": "Disabled rules whose sheet would not let them be enabled today (the sheet gate is not null)."
              },
              "items": {
                "type": "array",
                "maxItems": 10,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "name",
                    "device_id",
                    "kind",
                    "enabled",
                    "state",
                    "reason"
                  ],
                  "properties": {
                    "id": {
                      "type": "integer"
                    },
                    "name": {
                      "type": "string"
                    },
                    "device_id": {
                      "type": "string"
                    },
                    "kind": {
                      "type": "string",
                      "enum": [
                        "schedule",
                        "threshold",
                        "et0_budget",
                        "lighting"
                      ]
                    },
                    "enabled": {
                      "type": "boolean"
                    },
                    "state": {
                      "type": "string",
                      "enum": [
                        "disabled",
                        "ok",
                        "blocked",
                        "fallback"
                      ]
                    },
                    "reason": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "An enabled rule's state_reason (e.g. `no_signed_sheet`, `salinity_block`, `stale`); a disabled rule's sheet gate (e.g. `no_signed_sheet`, `sheet_expired`, `sheet_incomplete`)."
                    }
                  }
                },
                "description": "Blocked first, then on fallback, then not ready, each newest first."
              }
            }
          },
          "salinity": {
            "type": "object",
            "additionalProperties": false,
            "description": "The open alerts of a controller in scope whose zone's water or soil EC (mS/cm) passed its signed sheet's limit: `salinity_block` (high, the sheet's action blocked the zone's water) and `salinity_alert` (warning, the zone was watered as decided); their count and the newest 5.",
            "required": [
              "open",
              "items"
            ],
            "properties": {
              "open": {
                "type": "integer",
                "minimum": 0
              },
              "items": {
                "type": "array",
                "maxItems": 5,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "kind",
                    "severity",
                    "device_id",
                    "created_at"
                  ],
                  "properties": {
                    "id": {
                      "type": "integer"
                    },
                    "kind": {
                      "type": "string",
                      "enum": [
                        "salinity_block",
                        "salinity_alert"
                      ]
                    },
                    "severity": {
                      "type": "string",
                      "enum": [
                        "high",
                        "warning"
                      ]
                    },
                    "device_id": {
                      "type": "string"
                    },
                    "created_at": {
                      "type": "number"
                    }
                  }
                }
              }
            }
          },
          "et0": {
            "type": "object",
            "additionalProperties": false,
            "description": "Per weather station a zone in scope names, its latest stored reference ET0 day (meteorology only, as GET /v1/control/et0 answers it), by station.",
            "required": [
              "items"
            ],
            "properties": {
              "items": {
                "type": "array",
                "maxItems": 10,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "device_id",
                    "local_date",
                    "status",
                    "reason",
                    "et0_mm",
                    "hargreaves_mm",
                    "estimated"
                  ],
                  "properties": {
                    "device_id": {
                      "type": "string",
                      "description": "The weather station."
                    },
                    "local_date": {
                      "type": "string",
                      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
                      "description": "The local day (Asia/Ho_Chi_Minh, midnight to midnight)."
                    },
                    "status": {
                      "type": "string",
                      "enum": [
                        "ok",
                        "needs_krs",
                        "refused"
                      ],
                      "description": "`ok` with `et0_mm`; `needs_krs`: no measured radiation, each rule estimates it by eq. 50 with its own sheet's krs (the program's provenance has that ET0); `refused`: no ET0 (`reason`), the rule falls back."
                    },
                    "reason": {
                      "type": [
                        "string",
                        "null"
                      ],
                      "description": "Why not `ok`: station_not_approved, station_not_placed, temperature_coverage, out_of_range, sun_suspect, radiation_coverage, no_radiation."
                    },
                    "et0_mm": {
                      "type": [
                        "number",
                        "null"
                      ],
                      "minimum": 0,
                      "maximum": 15,
                      "description": "mm/day; null unless ok."
                    },
                    "hargreaves_mm": {
                      "type": [
                        "number",
                        "null"
                      ],
                      "description": "The trace's Hargreaves value (eq. 52), the paper's cross-check only; null when the stored day holds none."
                    },
                    "estimated": {
                      "type": "array",
                      "items": {
                        "type": "string",
                        "enum": [
                          "ea",
                          "u2",
                          "rs",
                          "rain"
                        ]
                      },
                      "description": "The inputs that are estimated."
                    }
                  }
                }
              }
            }
          }
        }
      },
      "ControlAdvisorySheet": {
        "type": "object",
        "additionalProperties": false,
        "description": "#354: a signed sheet in force today, with its lime and fertiliser advice as signed.",
        "required": [
          "sheet_id",
          "series_key",
          "crop",
          "version",
          "valid_from",
          "valid_to",
          "body_sha256",
          "signed_by",
          "signed_at",
          "advisory",
          "references",
          "growing_areas"
        ],
        "properties": {
          "sheet_id": {
            "type": "integer"
          },
          "series_key": {
            "type": "string"
          },
          "crop": {
            "type": "string"
          },
          "version": {
            "type": "integer"
          },
          "valid_from": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "valid_to": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "body_sha256": {
            "type": "string",
            "pattern": "^[0-9a-f]{64}$"
          },
          "signed_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "The signer's legal name as the attestation recorded it."
          },
          "signed_at": {
            "type": [
              "number",
              "null"
            ],
            "description": "When the attestation was signed."
          },
          "advisory": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "properties": {
              "lime": {
                "$ref": "#/components/schemas/AgronomyAdvisory"
              },
              "fertiliser": {
                "$ref": "#/components/schemas/AgronomyAdvisory"
              }
            },
            "description": "The body's advisory section exactly as signed; null when the sheet has none."
          },
          "references": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "type": "object",
              "additionalProperties": false,
              "properties": {
                "title": {
                  "type": "string",
                  "minLength": 1,
                  "maxLength": 200
                },
                "url": {
                  "type": "string",
                  "maxLength": 2000
                },
                "sha256": {
                  "type": "string",
                  "pattern": "^[0-9a-f]{64}$"
                }
              }
            },
            "description": "The body's references, as signed ([] when none)."
          },
          "growing_areas": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "type": "string"
            },
            "description": "The codes of the company's growing areas whose crop is the sheet's crop; [] for a caller who may not read the growing areas (an agronomist holding no role of growing_area_read)."
          }
        }
      },
      "ControlAdvisory": {
        "type": "object",
        "additionalProperties": false,
        "description": "#354: the lime and fertiliser advisory view (control/advisory.py): the advice of the signed sheets whose validity covers today and whose signature still holds, by series and version. No amount and no formula: a lab test is required.",
        "required": [
          "generated_at",
          "today",
          "items",
          "drafts",
          "withheld"
        ],
        "properties": {
          "generated_at": {
            "type": "number"
          },
          "today": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "items": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/ControlAdvisorySheet"
            }
          },
          "drafts": {
            "type": "integer",
            "minimum": 0,
            "description": "The company's draft sheets (never listed)."
          },
          "withheld": {
            "type": "integer",
            "minimum": 0,
            "description": "#354 review M5: the company's signed sheets in force today that are not listed because their signature can no longer be checked (the stored document no longer hashes to what was signed, or the signer is no longer verified); a count only, no detail."
          }
        }
      },
      "AgronomyTodayProgram": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "device_id",
          "status",
          "proposed_at",
          "sheets"
        ],
        "properties": {
          "id": {
            "type": "integer"
          },
          "device_id": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "proposed",
              "approved",
              "rejected",
              "dispatched",
              "superseded",
              "failed",
              "blocked",
              "expired",
              "withdrawn"
            ]
          },
          "proposed_at": {
            "type": "number"
          },
          "sheets": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "id",
                "version",
                "series_key"
              ],
              "properties": {
                "id": {
                  "type": "integer"
                },
                "version": {
                  "type": "integer"
                },
                "series_key": {
                  "type": "string"
                }
              }
            }
          }
        }
      },
      "AgronomyFallbackRule": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "rule_id",
          "rule_name",
          "device_id",
          "zones",
          "reason"
        ],
        "properties": {
          "rule_id": {
            "type": "integer"
          },
          "rule_name": {
            "type": "string"
          },
          "device_id": {
            "type": "string"
          },
          "zones": {
            "type": "array",
            "items": {
              "type": "integer"
            }
          },
          "reason": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "ProgramWithdrawalRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "reason"
        ],
        "description": "#367: why the person withdraws the controller's program, and the program they saw.",
        "properties": {
          "reason": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500,
            "description": "Why (required): 1 to 500 characters after trimming, without control characters but tab and newline, and without format characters (Unicode category Cf)."
          },
          "control_program_id": {
            "type": "integer",
            "minimum": 1,
            "description": "The control program the person saw (optional); it must be one of the device's programs. Whatever the controller holds now is withdrawn."
          }
        }
      },
      "ProgramWithdrawal": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "withdrawal",
          "control_program",
          "hold_until"
        ],
        "description": "#367: the withdrawal recorded as owed (and whether it was handed to the transport), the control program now withdrawn, and the end of the engine's hold. The controller's reports, never this answer, say the program stopped.",
        "properties": {
          "withdrawal": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "owed_at",
              "published"
            ],
            "properties": {
              "owed_at": {
                "type": "string",
                "format": "date-time",
                "description": "When the withdrawal was recorded as owed (RFC 3339 UTC)."
              },
              "published": {
                "type": "boolean",
                "description": "Whether it was handed to the transport now; when false it stays owed and is sent again until acknowledged (ADR 0011). The withdrawal is recorded whatever this says."
              }
            }
          },
          "control_program": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "id",
              "status",
              "program_version"
            ],
            "description": "The control program withdrawn; null when the controller held no control program in force (a set_program sent by hand, nothing on the controller any more, or a second withdrawal).",
            "properties": {
              "id": {
                "type": "integer"
              },
              "status": {
                "type": "string",
                "enum": [
                  "withdrawn"
                ]
              },
              "program_version": {
                "type": "integer"
              }
            }
          },
          "hold_until": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "The end of the engine's hold on the controller: the next farm-local midnight, or a later hold already set (RFC 3339 UTC)."
          }
        }
      },
      "ProgramHoldRelease": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "released",
          "rules_due"
        ],
        "description": "#367: the hold released before its end, and how many of the controller's enabled rules were made due (the engine composes them on its next run).",
        "properties": {
          "released": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "hold_until",
              "released_at"
            ],
            "properties": {
              "hold_until": {
                "type": "string",
                "format": "date-time",
                "description": "The end the hold had (RFC 3339 UTC)."
              },
              "released_at": {
                "type": "string",
                "format": "date-time",
                "description": "When it was released (RFC 3339 UTC)."
              }
            }
          },
          "rules_due": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "CockpitDay": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "date",
          "starts_at",
          "time_zone"
        ],
        "description": "#365: the farm day (Asia/Ho_Chi_Minh) an answer of the cockpit was computed in (common/farm_day.py).",
        "properties": {
          "date": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
            "description": "Its farm date."
          },
          "starts_at": {
            "type": "string",
            "format": "date-time",
            "description": "Its local midnight, in UTC."
          },
          "time_zone": {
            "type": "string",
            "enum": [
              "Asia/Ho_Chi_Minh"
            ]
          }
        }
      },
      "ControlZoneHistoryDay": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "date",
          "planned_l",
          "applied_l",
          "planned_mm",
          "applied_mm",
          "et0_mm",
          "et0_status",
          "kc_stage",
          "rain_mm",
          "rule",
          "program"
        ],
        "description": "#365: one farm day of a zone. Every value is null when its source is absent; none is ever filled in.",
        "properties": {
          "date": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "planned_l": {
            "type": [
              "number",
              "null"
            ],
            "description": "The litres the program in force planned for the zone from its dispatch on: the day's newest program that became a command, did not fail and whose command was not refused, unless the controller no longer ran it (a later row records its withdrawal, a person withdrew it, a withdrawal was asked for after its dispatch, or the controller reported it replaced or cancelled) or a person's own set_program (sent outside the engine, a higher version, not refused nor ended, not withdrawn since) was issued before the day ended (the engine's `holding` rule over a day, control/in_force.py, shared with the budget read); null without one, or when it planned nothing (blocked, no stage)."
          },
          "applied_l": {
            "type": [
              "number",
              "null"
            ],
            "description": "Litres the controller reported delivered to the zone that day (water.volume_delivered with meta.zone); null when it reported nothing, never 0 for no data."
          },
          "planned_mm": {
            "type": [
              "number",
              "null"
            ],
            "description": "`planned_l` over the zone's irrigated area (1 L/m2 = 1 mm), the water given, before efficiency."
          },
          "applied_mm": {
            "type": [
              "number",
              "null"
            ],
            "description": "`applied_l` over the zone's irrigated area, the basis of `planned_mm`."
          },
          "et0_mm": {
            "type": [
              "number",
              "null"
            ],
            "description": "Reference evapotranspiration of the day at the zone's weather station (FAO-56, #353): the latest stored version of the station day in et0_daily; null unless its status is `ok`, and without a station or a stored day."
          },
          "et0_status": {
            "type": [
              "string",
              "null"
            ],
            "description": "That station day's status: `ok`, `needs_krs` (no usable measured radiation: each rule estimates it with its sheet's krs, in the program's provenance) or `refused`; null without a station or a stored day.",
            "enum": [
              "ok",
              "needs_krs",
              "refused",
              null
            ]
          },
          "kc_stage": {
            "type": [
              "number",
              "null"
            ],
            "description": "The crop coefficient (Kc) the engine applied to the day's ET0: an et0_budget zone's record in a program of the next day, which sizes that day from this one (the Kc control_water_balance's ETc of the day was booked with); null without one."
          },
          "rain_mm": {
            "type": [
              "number",
              "null"
            ],
            "description": "The rain the station's inputs summed for the day (a partial day is a lower bound); null without a station or a stored day."
          },
          "rule": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "kind",
              "applied_as"
            ],
            "description": "How the newest program row of the day decided the zone; null without one.",
            "properties": {
              "kind": {
                "type": [
                  "string",
                  "null"
                ],
                "enum": [
                  "schedule",
                  "threshold",
                  "et0_budget",
                  "lighting",
                  null
                ]
              },
              "applied_as": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "As the program's provenance says: `schedule`, `schedule (fallback: frozen)`, `blocked: no_signed_sheet`..."
              }
            }
          },
          "program": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "id",
              "status"
            ],
            "description": "The newest program row of the day for the controller.",
            "properties": {
              "id": {
                "type": "integer"
              },
              "status": {
                "type": "string",
                "enum": [
                  "proposed",
                  "approved",
                  "rejected",
                  "dispatched",
                  "superseded",
                  "failed",
                  "blocked",
                  "expired"
                ]
              }
            }
          }
        }
      },
      "ControlZoneRun": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "started_at",
          "ended_at",
          "litres",
          "source",
          "command_id"
        ],
        "description": "#365: one delivery the controller reported for the zone (it reports a run's water when the run ends).",
        "properties": {
          "started_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "When the controller's `accepted` of a manual run arrived; null for a program step (a controller does not report a step's start)."
          },
          "ended_at": {
            "type": "string",
            "format": "date-time",
            "description": "The delivered-volume reading's time."
          },
          "litres": {
            "type": "number",
            "minimum": 0
          },
          "source": {
            "type": "string",
            "enum": [
              "manual",
              "program_step"
            ],
            "description": "`manual`: a run_zone of the controller completed within 15 minutes of the range, its final report with the same zone and litres within 15 minutes of the reading and its `accepted` no later than the reading; else `program_step`."
          },
          "command_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "The run_zone, or the set_program the controller accepted last before the reading, its lease not ended and not withdrawn since; null when none is known."
          }
        }
      },
      "ControlZoneBand": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "from",
          "to",
          "lower_pct",
          "upper_pct",
          "depth_cm",
          "probe_profile",
          "stage",
          "stage_name",
          "sheet"
        ],
        "description": "#365 (decision D3): a moisture target band of a stage of a signed sheet, clipped to the range and the sheet's validity. Only from a sheet signed now; never a default.",
        "properties": {
          "from": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "to": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "lower_pct": {
            "type": "number"
          },
          "upper_pct": {
            "type": "number"
          },
          "depth_cm": {
            "type": "number",
            "description": "The band's basis depth."
          },
          "probe_profile": {
            "type": [
              "string",
              "null"
            ],
            "description": "The probe profile the band was set for."
          },
          "stage": {
            "type": [
              "string",
              "null"
            ],
            "description": "The stage's code."
          },
          "stage_name": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/AgronomyLocalizedText"
              },
              {
                "type": "null"
              }
            ],
            "description": "#372: the stage's name as the sheet words it (vi, en, zh-Hans); null when the stage has none."
          },
          "sheet": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "id",
              "version",
              "series_key",
              "body_sha256"
            ],
            "properties": {
              "id": {
                "type": "integer"
              },
              "version": {
                "type": "integer"
              },
              "series_key": {
                "type": "string"
              },
              "body_sha256": {
                "type": "string"
              }
            }
          }
        }
      },
      "ControlZoneHistory": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "max_age_s",
          "poll_hint_s",
          "day",
          "from",
          "to",
          "zone",
          "days",
          "runs",
          "moisture_series",
          "moisture",
          "bands",
          "truncated"
        ],
        "description": "#365 (CP-5): a zone's water per farm day, its runs and the target bands of its signed sheets (control/cockpit/zone_history.py).",
        "properties": {
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it from its cache for `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "description": "How long the server serves this answer from its cache."
          },
          "poll_hint_s": {
            "type": "integer",
            "description": "How often a screen may ask again."
          },
          "day": {
            "$ref": "#/components/schemas/CockpitDay"
          },
          "from": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "to": {
            "type": "string",
            "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
          },
          "zone": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "device_id",
              "zone",
              "name",
              "area",
              "irrigated_area_m2"
            ],
            "properties": {
              "device_id": {
                "type": "string"
              },
              "zone": {
                "type": "integer",
                "minimum": 1,
                "maximum": 16
              },
              "name": {
                "type": "string"
              },
              "area": {
                "type": "string"
              },
              "irrigated_area_m2": {
                "type": "number",
                "exclusiveMinimum": 0
              }
            }
          },
          "days": {
            "type": "array",
            "maxItems": 92,
            "items": {
              "$ref": "#/components/schemas/ControlZoneHistoryDay"
            }
          },
          "runs": {
            "type": "array",
            "maxItems": 500,
            "description": "Newest first.",
            "items": {
              "$ref": "#/components/schemas/ControlZoneRun"
            }
          },
          "moisture_series": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "capability",
              "depth_cm",
              "grain"
            ],
            "description": "What the moisture chart reads from getSensorSeries for the zone's area; null when the zone has neither a band nor a probe.",
            "properties": {
              "capability": {
                "type": "string"
              },
              "depth_cm": {
                "type": "number"
              },
              "grain": {
                "type": "string",
                "enum": [
                  "hourly",
                  "local_daily"
                ]
              }
            }
          },
          "moisture": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": false,
            "required": [
              "capability",
              "grain",
              "bucket_s",
              "probes",
              "series",
              "truncated"
            ],
            "description": "#372: the soil moisture of the zone's own probes (its `probes`), read under the zone's scope: one series per probe depth, the basis depth (the first band's, else the first probe's) first, the probes at one depth merged; buckets of an hour up to 14 days, else of a farm day (Asia/Ho_Chi_Minh). Only readings that carry a value are counted (`n_missing` is 0). Null when the zone names no probe.",
            "properties": {
              "capability": {
                "type": "string",
                "const": "soil.moisture"
              },
              "grain": {
                "type": "string",
                "enum": [
                  "hourly",
                  "local_daily"
                ]
              },
              "bucket_s": {
                "type": "number",
                "description": "3600 (hourly) or 86400 (a farm day)."
              },
              "probes": {
                "type": "array",
                "items": {
                  "type": "string"
                },
                "description": "The zone's probes read."
              },
              "series": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/SensorSeriesDepth"
                }
              },
              "truncated": {
                "type": "boolean",
                "description": "More than 20,000 readings: the oldest were left out."
              }
            }
          },
          "bands": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ControlZoneBand"
            }
          },
          "truncated": {
            "type": "boolean",
            "description": "True when older runs than the 500 newest, or more than 5000 set_program commands of the range, were left out."
          }
        },
        "example": {
          "generated_at": "2027-03-02T03:15:00Z",
          "max_age_s": 60,
          "poll_hint_s": 60,
          "day": {
            "date": "2027-03-02",
            "starts_at": "2027-03-01T17:00:00Z",
            "time_zone": "Asia/Ho_Chi_Minh"
          },
          "from": "2027-03-01",
          "to": "2027-03-02",
          "zone": {
            "device_id": "irr-ph7-01",
            "zone": 3,
            "name": "Block A",
            "area": "VN-TGOR-0387",
            "irrigated_area_m2": 120.0
          },
          "days": [
            {
              "date": "2027-03-01",
              "planned_l": 216.0,
              "applied_l": 216.0,
              "planned_mm": 1.8,
              "applied_mm": 1.8,
              "et0_mm": null,
              "et0_status": null,
              "kc_stage": null,
              "rain_mm": null,
              "rule": {
                "kind": "schedule",
                "applied_as": "schedule"
              },
              "program": {
                "id": 30,
                "status": "dispatched"
              }
            },
            {
              "date": "2027-03-02",
              "planned_l": null,
              "applied_l": null,
              "planned_mm": null,
              "applied_mm": null,
              "et0_mm": null,
              "et0_status": null,
              "kc_stage": null,
              "rain_mm": null,
              "rule": {
                "kind": "schedule",
                "applied_as": "blocked: no_signed_sheet"
              },
              "program": {
                "id": 31,
                "status": "blocked"
              }
            }
          ],
          "runs": [
            {
              "started_at": null,
              "ended_at": "2027-03-01T13:30:00Z",
              "litres": 216.0,
              "source": "program_step",
              "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f"
            }
          ],
          "moisture_series": {
            "capability": "soil.moisture",
            "depth_cm": 30.0,
            "grain": "hourly"
          },
          "moisture": {
            "capability": "soil.moisture",
            "grain": "hourly",
            "bucket_s": 3600.0,
            "probes": [
              "soil-07"
            ],
            "truncated": false,
            "series": [
              {
                "depth_cm": 30.0,
                "buckets": [
                  {
                    "bucket_start": 1803906000.0,
                    "min": 30.7,
                    "max": 31.1,
                    "mean": 30.9,
                    "count": 2,
                    "n_total": 2,
                    "n_pass": 2,
                    "n_not_evaluated": 0,
                    "n_suspect": 0,
                    "n_fail": 0,
                    "n_missing": 0
                  },
                  {
                    "bucket_start": 1803909600.0,
                    "min": null,
                    "max": null,
                    "mean": null,
                    "count": 0,
                    "n_total": 1,
                    "n_pass": 0,
                    "n_not_evaluated": 0,
                    "n_suspect": 0,
                    "n_fail": 1,
                    "n_missing": 0
                  }
                ]
              }
            ]
          },
          "bands": [],
          "truncated": false
        }
      },
      "ControlProbeHealth": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "device_id",
          "profile",
          "depth_cm",
          "capability",
          "link",
          "coverage_30d_pct",
          "qc_30d",
          "used_by"
        ],
        "description": "#365: one probe of the area at one depth.",
        "properties": {
          "device_id": {
            "type": "string"
          },
          "profile": {
            "type": "string"
          },
          "depth_cm": {
            "type": [
              "number",
              "null"
            ]
          },
          "capability": {
            "type": [
              "string",
              "null"
            ],
            "description": "The series judged: soil.moisture for a probe a zone names (the series the health gate reads); for a field sensor no zone names, soil.moisture when its profile produces it, else its first capability."
          },
          "link": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "last_obs",
              "expected_s"
            ],
            "description": "The health gate's freshness rule (decision D11): fresh up to 2 poll intervals (at most 1800 s) after the latest reading of any area (which has a value), stale up to 10 poll intervals, offline past that or without a reading.",
            "properties": {
              "state": {
                "type": "string",
                "enum": [
                  "fresh",
                  "stale",
                  "offline"
                ]
              },
              "last_obs": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time"
              },
              "expected_s": {
                "type": "number",
                "description": "The profile's poll interval."
              }
            }
          },
          "coverage_30d_pct": {
            "type": "number",
            "minimum": 0,
            "maximum": 100,
            "description": "Whole hours of the last 720 holding a usable reading (QC pass or not evaluated, a value, Device-recorded), by the reading's own time."
          },
          "qc_30d": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "pass",
              "not_evaluated",
              "suspect",
              "fail",
              "missing"
            ],
            "properties": {
              "pass": {
                "type": "integer",
                "minimum": 0
              },
              "not_evaluated": {
                "type": "integer",
                "minimum": 0
              },
              "suspect": {
                "type": "integer",
                "minimum": 0
              },
              "fail": {
                "type": "integer",
                "minimum": 0
              },
              "missing": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "used_by": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "rule_id",
                "device_id",
                "zones",
                "state",
                "since"
              ],
              "description": "An enabled threshold rule whose zones name the probe at this depth.",
              "properties": {
                "rule_id": {
                  "type": "integer"
                },
                "device_id": {
                  "type": "string"
                },
                "zones": {
                  "type": "array",
                  "items": {
                    "type": "integer"
                  }
                },
                "state": {
                  "type": "string",
                  "description": "`ok`, `blocked:<reason>` or `fallback:<reason>`."
                },
                "since": {
                  "type": [
                    "string",
                    "null"
                  ],
                  "format": "date-time"
                }
              }
            }
          }
        }
      },
      "ControlSensorHealth": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "max_age_s",
          "poll_hint_s",
          "day",
          "area",
          "probes",
          "gate_decisions_today",
          "truncated"
        ],
        "description": "#365 (CP-5): a growing area's probes, the rules that read them and today's gate decisions (control/cockpit/sensor_health.py).",
        "properties": {
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it from its cache for `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "description": "How long the server serves this answer from its cache."
          },
          "poll_hint_s": {
            "type": "integer",
            "description": "How often a screen may ask again."
          },
          "day": {
            "$ref": "#/components/schemas/CockpitDay"
          },
          "area": {
            "type": "string"
          },
          "probes": {
            "type": "array",
            "maxItems": 200,
            "items": {
              "$ref": "#/components/schemas/ControlProbeHealth"
            }
          },
          "gate_decisions_today": {
            "type": "array",
            "maxItems": 200,
            "description": "Newest first.",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "required": [
                "rule_id",
                "device_id",
                "zone",
                "decision",
                "reason",
                "at"
              ],
              "properties": {
                "rule_id": {
                  "type": "integer"
                },
                "device_id": {
                  "type": "string"
                },
                "zone": {
                  "type": "integer"
                },
                "decision": {
                  "type": "string",
                  "enum": [
                    "healthy",
                    "fallback",
                    "blocked"
                  ]
                },
                "reason": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "at": {
                  "type": "string",
                  "format": "date-time"
                }
              }
            }
          },
          "truncated": {
            "type": "boolean",
            "description": "True when more than 200 probes, or more than 200 of the caller's gate decisions of today, were left out."
          }
        },
        "example": {
          "generated_at": "2027-03-02T03:15:00Z",
          "max_age_s": 300,
          "poll_hint_s": 300,
          "day": {
            "date": "2027-03-02",
            "starts_at": "2027-03-01T17:00:00Z",
            "time_zone": "Asia/Ho_Chi_Minh"
          },
          "area": "VN-TGOR-0387",
          "probes": [
            {
              "device_id": "soil-07",
              "profile": "vn.agritrace.soil-rs485-4in1",
              "depth_cm": 30.0,
              "capability": "soil.moisture",
              "link": {
                "state": "stale",
                "last_obs": "2027-03-02T01:10:00Z",
                "expected_s": 900.0
              },
              "coverage_30d_pct": 96.1,
              "qc_30d": {
                "pass": 2710,
                "not_evaluated": 0,
                "suspect": 12,
                "fail": 3,
                "missing": 0
              },
              "used_by": [
                {
                  "rule_id": 14,
                  "device_id": "irr-ph7-01",
                  "zones": [
                    3
                  ],
                  "state": "fallback:stale",
                  "since": "2027-03-02T02:00:00Z"
                }
              ]
            }
          ],
          "gate_decisions_today": [
            {
              "rule_id": 14,
              "device_id": "irr-ph7-01",
              "zone": 3,
              "decision": "fallback",
              "reason": "stale",
              "at": "2027-03-02T02:00:00Z"
            }
          ],
          "truncated": false
        }
      },
      "AlarmView": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "kind",
          "catalog_version",
          "priority",
          "state",
          "raised_at",
          "last_active_at",
          "cleared_at",
          "closed_at",
          "occurrences",
          "acked",
          "shelved",
          "subject",
          "detail",
          "response_anchor",
          "under"
        ],
        "description": "#361 (ADR 0015, the alarm philosophy): one alarm of the company, a condition with a lifecycle (control/cockpit/alarms). Its `state` is derived from the stored times: `closed` once closed (cleared and acknowledged, or a notice cleared), else `shelved` while `shelved.until` is ahead, else `active_unacked`, `active_acked` or `cleared_unacked`. Times are RFC 3339 UTC.",
        "properties": {
          "id": {
            "type": "integer"
          },
          "kind": {
            "type": "string",
            "description": "The catalog kind (catalog v1: command_refused_security, controller_fault, delivered_over_limit, sheet_hash_mismatch, controller_offline, program_not_installed, command_refused_site, run_no_water, step_missed, rule_blocked, salinity_block, rule_on_fallback, probe_stale_in_use, moisture_outside_band). The catalog grows under management of change (the philosophy), so a client words an unknown kind by its token."
          },
          "catalog_version": {
            "type": "integer",
            "minimum": 1,
            "description": "The catalog version the alarm was raised under."
          },
          "priority": {
            "type": "string",
            "enum": [
              "urgent",
              "warning",
              "notice"
            ]
          },
          "state": {
            "type": "string",
            "enum": [
              "active_unacked",
              "active_acked",
              "cleared_unacked",
              "shelved",
              "closed"
            ]
          },
          "raised_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the condition was first raised (after its on-delay)."
          },
          "last_active_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the condition was last seen true."
          },
          "cleared_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "When the condition returned to normal (after its clear-delay); null while active. A re-raise within 30 minutes of clearing (not closed) reuses the alarm and empties it again."
          },
          "closed_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "occurrences": {
            "type": "integer",
            "minimum": 1,
            "description": "How many times the condition was raised on this alarm (chatter control)."
          },
          "acked": {
            "anyOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "at",
                  "by",
                  "note"
                ],
                "properties": {
                  "at": {
                    "type": "string",
                    "format": "date-time"
                  },
                  "by": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "Who acknowledged it: the member's display name, or their sign-in when they have none. Null for an agronomist (#363: they read alarms, not who handled them; the note is null too)."
                  },
                  "note": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "maxLength": 500
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          },
          "shelved": {
            "anyOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "until",
                  "by",
                  "reason",
                  "note"
                ],
                "properties": {
                  "until": {
                    "type": "string",
                    "format": "date-time"
                  },
                  "by": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "Who did it. Null for an agronomist (#363: they read alarms, not who handled them; the note is null too)."
                  },
                  "reason": {
                    "type": "string",
                    "enum": [
                      "maintenance",
                      "technician_called",
                      "known_issue",
                      "equipment_off",
                      "other"
                    ]
                  },
                  "note": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "maxLength": 200
                  }
                }
              },
              {
                "type": "null"
              }
            ],
            "description": "The current shelving, null when the alarm is not shelved (or its shelving ended)."
          },
          "subject": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "type",
              "device",
              "zone",
              "area"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "device",
                  "zone",
                  "area",
                  "rule",
                  "program"
                ]
              },
              "device": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "zone": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 1
              },
              "area": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The growing area code."
              }
            }
          },
          "detail": {
            "type": "object",
            "additionalProperties": true,
            "description": "Facts the platform observed (the command id and its refusal reason, the measured litres and the command's max_volume_l, the controller's faults, when its gateway was last heard), at most 2 KB, never coordinates."
          },
          "response_anchor": {
            "type": "string",
            "description": "The anchor of the alarm's documented response in the alarm philosophy (the kind)."
          },
          "under": {
            "type": [
              "integer",
              "null"
            ],
            "description": "Suppression by design, computed when read: the id of the open `controller_offline` alarm of the same controller this alarm is shown under; null otherwise."
          }
        }
      },
      "AlarmEvent": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "at",
          "event",
          "actor",
          "reason"
        ],
        "description": "#361: one change of an alarm's state (`alarm_events`, append-only).",
        "properties": {
          "at": {
            "type": "string",
            "format": "date-time"
          },
          "event": {
            "type": "string",
            "enum": [
              "raised",
              "reraised",
              "cleared",
              "acked",
              "shelved",
              "unshelved",
              "shelve_expired",
              "closed"
            ]
          },
          "actor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The person (display name, or sign-in when they have none), or `system` for the evaluator. Null for a person when an agronomist reads it (#363)."
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "A code only: for `shelved`, the shelving's reason code (`maintenance`, `technician_called`, `known_issue`, `equipment_off` or `other`); null for every other event. The acknowledgement's note and the shelving's note are the alarm's (`acked.note`, `shelved.note`), never the history's, so they can be erased with the person's data."
          }
        }
      },
      "AlarmDetail": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "kind",
          "catalog_version",
          "priority",
          "state",
          "raised_at",
          "last_active_at",
          "cleared_at",
          "closed_at",
          "occurrences",
          "acked",
          "shelved",
          "subject",
          "detail",
          "response_anchor",
          "under",
          "events",
          "events_truncated"
        ],
        "description": "#361: an alarm (AlarmView) with its history: `events`, oldest first, at most the 100 newest (`events_truncated` when older ones exist).",
        "properties": {
          "id": {
            "type": "integer"
          },
          "kind": {
            "type": "string",
            "description": "The catalog kind (catalog v1: command_refused_security, controller_fault, delivered_over_limit, sheet_hash_mismatch, controller_offline, program_not_installed, command_refused_site, run_no_water, step_missed, rule_blocked, salinity_block, rule_on_fallback, probe_stale_in_use, moisture_outside_band). The catalog grows under management of change (the philosophy), so a client words an unknown kind by its token."
          },
          "catalog_version": {
            "type": "integer",
            "minimum": 1,
            "description": "The catalog version the alarm was raised under."
          },
          "priority": {
            "type": "string",
            "enum": [
              "urgent",
              "warning",
              "notice"
            ]
          },
          "state": {
            "type": "string",
            "enum": [
              "active_unacked",
              "active_acked",
              "cleared_unacked",
              "shelved",
              "closed"
            ]
          },
          "raised_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the condition was first raised (after its on-delay)."
          },
          "last_active_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the condition was last seen true."
          },
          "cleared_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "When the condition returned to normal (after its clear-delay); null while active. A re-raise within 30 minutes of clearing (not closed) reuses the alarm and empties it again."
          },
          "closed_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "occurrences": {
            "type": "integer",
            "minimum": 1,
            "description": "How many times the condition was raised on this alarm (chatter control)."
          },
          "acked": {
            "anyOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "at",
                  "by",
                  "note"
                ],
                "properties": {
                  "at": {
                    "type": "string",
                    "format": "date-time"
                  },
                  "by": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "Who acknowledged it: the member's display name, or their sign-in when they have none. Null for an agronomist (#363: they read alarms, not who handled them; the note is null too)."
                  },
                  "note": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "maxLength": 500
                  }
                }
              },
              {
                "type": "null"
              }
            ]
          },
          "shelved": {
            "anyOf": [
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "until",
                  "by",
                  "reason",
                  "note"
                ],
                "properties": {
                  "until": {
                    "type": "string",
                    "format": "date-time"
                  },
                  "by": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "Who did it. Null for an agronomist (#363: they read alarms, not who handled them; the note is null too)."
                  },
                  "reason": {
                    "type": "string",
                    "enum": [
                      "maintenance",
                      "technician_called",
                      "known_issue",
                      "equipment_off",
                      "other"
                    ]
                  },
                  "note": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "maxLength": 200
                  }
                }
              },
              {
                "type": "null"
              }
            ],
            "description": "The current shelving, null when the alarm is not shelved (or its shelving ended)."
          },
          "subject": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "type",
              "device",
              "zone",
              "area"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "device",
                  "zone",
                  "area",
                  "rule",
                  "program"
                ]
              },
              "device": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "zone": {
                "type": [
                  "integer",
                  "null"
                ],
                "minimum": 1
              },
              "area": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "The growing area code."
              }
            }
          },
          "detail": {
            "type": "object",
            "additionalProperties": true,
            "description": "Facts the platform observed (the command id and its refusal reason, the measured litres and the command's max_volume_l, the controller's faults, when its gateway was last heard), at most 2 KB, never coordinates."
          },
          "response_anchor": {
            "type": "string",
            "description": "The anchor of the alarm's documented response in the alarm philosophy (the kind)."
          },
          "under": {
            "type": [
              "integer",
              "null"
            ],
            "description": "Suppression by design, computed when read: the id of the open `controller_offline` alarm of the same controller this alarm is shown under; null otherwise."
          },
          "events": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/AlarmEvent"
            }
          },
          "events_truncated": {
            "type": "boolean"
          }
        }
      },
      "AlarmPage": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "items",
          "next_cursor",
          "counts"
        ],
        "properties": {
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AlarmView"
            }
          },
          "next_cursor": {
            "type": [
              "string",
              "null"
            ],
            "description": "The next page's `cursor`; null on the last page."
          },
          "counts": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/AlarmCounts"
              },
              {
                "type": "null"
              }
            ],
            "description": "With `state=open`: the open alarms the caller may read, by priority, over every page (not this page only); null with `state=closed`."
          }
        }
      },
      "AlarmAck": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "note": {
            "type": "string",
            "maxLength": 500,
            "description": "Optional: what the person did or will do."
          }
        }
      },
      "AlarmShelve": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "until",
          "reason"
        ],
        "properties": {
          "until": {
            "type": "string",
            "format": "date-time",
            "description": "When the shelving ends: in the future, and at most 12 hours ahead for an urgent alarm, 72 hours for a warning or a notice."
          },
          "reason": {
            "type": "string",
            "enum": [
              "maintenance",
              "technician_called",
              "known_issue",
              "equipment_off",
              "other"
            ]
          },
          "note": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200,
            "description": "Free text; required when `reason` is `other`."
          }
        }
      },
      "ControlDay": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "date",
          "starts_at",
          "time_zone"
        ],
        "properties": {
          "date": {
            "type": "string",
            "format": "date",
            "description": "The farm-local date (Asia/Ho_Chi_Minh)."
          },
          "starts_at": {
            "type": "string",
            "format": "date-time",
            "description": "Its local midnight, in UTC (17:00:00Z of the day before)."
          },
          "time_zone": {
            "type": "string",
            "enum": [
              "Asia/Ho_Chi_Minh"
            ],
            "description": "The farm time zone every time of the answer is shown in."
          }
        },
        "description": "#363. The farm-local day an answer describes (the backend owns the day).",
        "example": {
          "date": "2026-10-22",
          "starts_at": "2026-10-21T17:00:00Z",
          "time_zone": "Asia/Ho_Chi_Minh"
        }
      },
      "ControlLink": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "state",
          "via",
          "gateway",
          "heard_at",
          "expected_s",
          "ready"
        ],
        "properties": {
          "state": {
            "type": "string",
            "enum": [
              "online",
              "stale",
              "offline",
              "unknown"
            ],
            "description": "Through a gateway: `online` (its heartbeat at most 90 s old lists the controller ready), `stale` (older, or not listing it ready), `offline` (no heartbeat within 300 s); `unknown` for a directly connected controller (no heartbeat: link not measured)."
          },
          "via": {
            "type": "string",
            "enum": [
              "gateway",
              "direct"
            ]
          },
          "gateway": {
            "type": [
              "string",
              "null"
            ],
            "description": "The gateway of the freshest heartbeat."
          },
          "heard_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "When the server received that heartbeat."
          },
          "expected_s": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The gateway's heartbeat interval; null for a direct link."
          },
          "ready": {
            "type": [
              "boolean",
              "null"
            ],
            "description": "Whether the heartbeat lists the controller ready (null when not measured)."
          }
        },
        "description": "#363. How a controller is reached, as its gateway reported it.",
        "example": {
          "state": "online",
          "via": "gateway",
          "gateway": "gw-v3",
          "heard_at": "2026-10-22T07:31:50Z",
          "expected_s": 30,
          "ready": true
        }
      },
      "ControlProgramToday": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "state",
          "command_id",
          "program_version",
          "control_program_id",
          "valid_until",
          "withdrawable",
          "withdraw_effect",
          "lease_version",
          "lease_command_id",
          "lease_control_program_id",
          "withdrawal"
        ],
        "properties": {
          "state": {
            "type": "string",
            "enum": [
              "none",
              "sending",
              "installed",
              "refused",
              "not_installed",
              "ended"
            ],
            "description": "The day's newest set_program as the controller reported it."
          },
          "command_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "program_version": {
            "type": [
              "integer",
              "null"
            ]
          },
          "control_program_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "The #352 program row that sent it (null: not the rules')."
          },
          "valid_until": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "The end of its lease."
          },
          "withdrawable": {
            "type": "boolean",
            "description": "Whether a withdrawal (POST /v1/devices/{id}/program-withdrawal) would be accepted now: a lease in force, a set_program waiting for the controller, or a rule or proposal to hold (#371: before, a lease in force only)."
          },
          "withdraw_effect": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "stop_installed",
              "stop_sending",
              "hold",
              "already_held",
              null
            ],
            "description": "#371: what a withdrawal would do now: `stop_installed` (the controller stops the program it holds), `stop_sending` (the set_program still waiting for the controller is withdrawn before it is taken), `hold` (nothing on the controller: the engine is held for the rest of the farm-local day); null when it would answer 409 `no_program`. `already_held` (#367 cross-review INFO 5): the controller is held already and nothing else is in force; a withdrawal answers 202 again, idempotently, and the hold stays as it is."
          },
          "lease_version": {
            "type": [
              "integer",
              "null"
            ],
            "description": "#371: the program_version of the program the controller holds now (its lease in force), which the day's newest set_program may not be; null when none is installed."
          },
          "lease_command_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "#371: the set_program command of that program; null when none is installed."
          },
          "lease_control_program_id": {
            "type": [
              "integer",
              "null"
            ],
            "description": "#371: the #352 program row that sent that program (null: none installed, or not the rules')."
          },
          "withdrawal": {
            "oneOf": [
              {
                "type": "null"
              },
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "requested_at",
                  "published",
                  "reason"
                ],
                "properties": {
                  "requested_at": {
                    "type": "string",
                    "format": "date-time",
                    "description": "When the withdrawal was asked for (the program row's withdrawn_at, or the platform's program_withdrawals row)."
                  },
                  "published": {
                    "type": "boolean",
                    "description": "Whether the platform published it to the controller (the broker took it); false while it is still owed. The controller's own reports (the program `aborted: cancelled`, its steps stopping) come after."
                  },
                  "reason": {
                    "type": [
                      "string",
                      "null"
                    ],
                    "description": "The reason the person gave; null to an agronomist, and for a withdrawal no person made."
                  }
                }
              }
            ],
            "description": "#367 cross-review M2: the withdrawal of the controller's program asked for since its lease was accepted (today when it has none); null when there is none."
          }
        },
        "description": "#363. Today's program of a controller.",
        "example": {
          "state": "installed",
          "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
          "program_version": 41,
          "control_program_id": 31,
          "valid_until": "2026-10-22T17:00:00Z",
          "withdrawable": true,
          "withdraw_effect": "stop_installed",
          "lease_version": 41,
          "lease_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
          "lease_control_program_id": 31,
          "withdrawal": null
        }
      },
      "ControlZoneToday": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "zone",
          "name",
          "state",
          "source",
          "since",
          "expected_end",
          "reason",
          "today",
          "moisture"
        ],
        "properties": {
          "zone": {
            "type": "integer",
            "minimum": 1,
            "maximum": 16
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "state": {
            "type": "string",
            "enum": [
              "idle",
              "requested",
              "running",
              "scheduled_now",
              "ended",
              "refused",
              "fault"
            ],
            "description": "From the reports only: a request waiting for the controller is `requested`, never `running`; a program step in its window is `scheduled_now` (the controllers report no step start)."
          },
          "source": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "run_zone_reply",
              "step_water",
              "program_reply",
              null
            ]
          },
          "since": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "expected_end": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "The refusal or fault reason token."
          },
          "today": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "applied_l",
              "planned_l",
              "runs"
            ],
            "properties": {
              "applied_l": {
                "type": "number",
                "minimum": 0,
                "description": "Litres the controller reported delivered today."
              },
              "planned_l": {
                "type": [
                  "number",
                  "null"
                ],
                "description": "Litres the #243 rules planned for the zone today; null whenever there is no plan, never 0."
              },
              "runs": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "moisture": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "value_pct",
              "obs_time",
              "band"
            ],
            "properties": {
              "state": {
                "type": "string",
                "enum": [
                  "below_band",
                  "in_band",
                  "above_band",
                  "no_band",
                  "stale",
                  "no_reading",
                  "no_probe"
                ]
              },
              "value_pct": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "obs_time": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time"
              },
              "band": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "lower_pct",
                  "upper_pct",
                  "sheet"
                ],
                "properties": {
                  "lower_pct": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "upper_pct": {
                    "type": [
                      "number",
                      "null"
                    ]
                  },
                  "sheet": {
                    "oneOf": [
                      {
                        "type": "null"
                      },
                      {
                        "type": "object",
                        "additionalProperties": false,
                        "required": [
                          "id",
                          "version",
                          "stage"
                        ],
                        "properties": {
                          "id": {
                            "type": "integer"
                          },
                          "version": {
                            "type": "integer"
                          },
                          "stage": {
                            "type": [
                              "string",
                              "null"
                            ]
                          }
                        }
                      }
                    ],
                    "description": "The signed sheet the band is from, and its stage of today."
                  }
                },
                "description": "The refill and full points of the signed agronomy sheet for today's stage (decision D3); every value null without a signed sheet band (no default is ever used)."
              }
            }
          },
          "sheet": {
            "description": "#373: the sheet the zone's enabled rule is bound to, whatever today's band, the rule's state or the sheet's status; null when no enabled rule binds a sheet. `status` is `signed` only while today is within the sheet's validity, `expired` past its last valid day and `not_yet_valid` before its first, else the sheet's own (`draft`, `superseded`, `revoked`). `stage` and `stage_name` are the stage covering today, else null. Optional in the schema, always sent.",
            "oneOf": [
              {
                "type": "null"
              },
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "id",
                  "status",
                  "version",
                  "stage",
                  "stage_name"
                ],
                "properties": {
                  "id": {
                    "type": "integer"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "signed",
                      "expired",
                      "not_yet_valid",
                      "draft",
                      "superseded",
                      "revoked"
                    ]
                  },
                  "version": {
                    "type": "integer"
                  },
                  "stage": {
                    "type": [
                      "string",
                      "null"
                    ]
                  },
                  "stage_name": {
                    "oneOf": [
                      {
                        "type": "null"
                      },
                      {
                        "$ref": "#/components/schemas/AgronomyLocalizedText"
                      }
                    ]
                  }
                }
              }
            ]
          },
          "nominal_flow_lpm": {
            "type": [
              "number",
              "null"
            ],
            "description": "Controller today only: the installation's nominal flow (#352 control_zones)."
          },
          "max_daily_l": {
            "type": [
              "number",
              "null"
            ],
            "description": "Controller today only: the zone's daily cap (#352 control_zones)."
          }
        },
        "description": "#363. A zone of a controller today.",
        "example": {
          "zone": 3,
          "name": "Rows 1-4",
          "state": "running",
          "source": "run_zone_reply",
          "since": "2026-10-22T07:03:00Z",
          "expected_end": "2026-10-22T07:23:00Z",
          "reason": null,
          "today": {
            "applied_l": 840.0,
            "planned_l": null,
            "runs": 1
          },
          "moisture": {
            "state": "no_band",
            "value_pct": 28.4,
            "obs_time": "2026-10-22T07:26:00Z",
            "band": {
              "lower_pct": null,
              "upper_pct": null,
              "sheet": null
            }
          }
        }
      },
      "ControlStepToday": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "zone",
          "start_s",
          "duration_s",
          "max_volume_l",
          "planned_l",
          "actual"
        ],
        "properties": {
          "zone": {
            "type": "integer",
            "minimum": 1,
            "maximum": 16
          },
          "start_s": {
            "type": "integer",
            "minimum": 0,
            "maximum": 86399,
            "description": "Seconds after local midnight."
          },
          "duration_s": {
            "type": "integer",
            "minimum": 1
          },
          "max_volume_l": {
            "type": [
              "number",
              "null"
            ]
          },
          "planned_l": {
            "type": [
              "number",
              "null"
            ]
          },
          "actual": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "litres",
              "ended_at"
            ],
            "properties": {
              "state": {
                "type": "string",
                "enum": [
                  "pending",
                  "done",
                  "missed",
                  "skipped",
                  "aborted",
                  "withdrawn"
                ],
                "description": "`withdrawn` (#367 cross-review M3): the step starts after a withdrawal of the lease asked for since its acceptance and delivered nothing; never `pending` or `missed`."
              },
              "litres": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "ended_at": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time"
              }
            }
          }
        },
        "description": "#363. A step of the controller's lease today, with what was observed of it.",
        "example": {
          "zone": 3,
          "start_s": 21600,
          "duration_s": 1200,
          "max_volume_l": 2625,
          "planned_l": null,
          "actual": {
            "state": "done",
            "litres": 1980.0,
            "ended_at": "2026-10-21T23:20:40Z"
          }
        }
      },
      "ControlCommandToday": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "id",
          "name",
          "status",
          "issued_by",
          "issued_at",
          "params",
          "expires_at",
          "reason",
          "measured"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "sent",
              "accepted",
              "completed",
              "aborted",
              "rejected",
              "expired",
              "failed"
            ]
          },
          "issued_by": {
            "type": [
              "string",
              "null"
            ],
            "description": "The person's display name (`system` for the engine); null for a caller who may not read the device (an agronomist)."
          },
          "issued_at": {
            "type": "string",
            "format": "date-time"
          },
          "params": {
            "type": "object",
            "additionalProperties": true
          },
          "expires_at": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "reason": {
            "type": [
              "string",
              "null"
            ]
          },
          "measured": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true
          }
        },
        "description": "#363. One of a controller's newest actuation commands.",
        "example": {
          "id": "9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f",
          "name": "run_zone",
          "status": "accepted",
          "issued_by": "Lan",
          "issued_at": "2026-10-22T07:02:10Z",
          "params": {
            "zone": 3,
            "duration_s": 1200,
            "max_volume_l": 2000
          },
          "expires_at": "2026-10-22T07:07:10Z",
          "reason": null,
          "measured": null
        }
      },
      "ControlControllerToday": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "device_id",
          "name",
          "link",
          "hold_until",
          "program",
          "zones",
          "steps",
          "commands"
        ],
        "properties": {
          "device_id": {
            "type": "string"
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "link": {
            "$ref": "#/components/schemas/ControlLink"
          },
          "hold_until": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "#367 cross-review M2: the end of the controller's hold in force (a person withdrew today's program; the engine sends nothing automatic until then), or null."
          },
          "program": {
            "$ref": "#/components/schemas/ControlProgramToday"
          },
          "zones": {
            "type": "array",
            "maxItems": 16,
            "items": {
              "$ref": "#/components/schemas/ControlZoneToday"
            }
          },
          "steps": {
            "type": "array",
            "maxItems": 48,
            "items": {
              "$ref": "#/components/schemas/ControlStepToday"
            }
          },
          "commands": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/ControlCommandToday"
            }
          }
        },
        "description": "#363. One controller of an area's day.",
        "example": {
          "device_id": "ctl-03",
          "name": "Controller 3",
          "link": {
            "state": "online",
            "via": "gateway",
            "gateway": "gw-v3",
            "heard_at": "2026-10-22T07:31:50Z",
            "expected_s": 30,
            "ready": true
          },
          "hold_until": null,
          "program": {
            "state": "installed",
            "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
            "program_version": 41,
            "control_program_id": 31,
            "valid_until": "2026-10-22T17:00:00Z",
            "withdrawable": true,
            "withdraw_effect": "stop_installed",
            "lease_version": 41,
            "lease_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
            "lease_control_program_id": 31,
            "withdrawal": null
          },
          "zones": [
            {
              "zone": 3,
              "name": "Rows 1-4",
              "state": "running",
              "source": "run_zone_reply",
              "since": "2026-10-22T07:03:00Z",
              "expected_end": "2026-10-22T07:23:00Z",
              "reason": null,
              "today": {
                "applied_l": 840.0,
                "planned_l": null,
                "runs": 1
              },
              "moisture": {
                "state": "no_band",
                "value_pct": 28.4,
                "obs_time": "2026-10-22T07:26:00Z",
                "band": {
                  "lower_pct": null,
                  "upper_pct": null,
                  "sheet": null
                }
              }
            }
          ],
          "steps": [
            {
              "zone": 3,
              "start_s": 21600,
              "duration_s": 1200,
              "max_volume_l": 2625,
              "planned_l": null,
              "actual": {
                "state": "done",
                "litres": 1980.0,
                "ended_at": "2026-10-21T23:20:40Z"
              }
            }
          ],
          "commands": [
            {
              "id": "9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f",
              "name": "run_zone",
              "status": "accepted",
              "issued_by": "Lan",
              "issued_at": "2026-10-22T07:02:10Z",
              "params": {
                "zone": 3,
                "duration_s": 1200,
                "max_volume_l": 2000
              },
              "expires_at": "2026-10-22T07:07:10Z",
              "reason": null,
              "measured": null
            }
          ]
        }
      },
      "ControlAreaToday": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "max_age_s",
          "poll_hint_s",
          "day",
          "area",
          "controllers",
          "truncated"
        ],
        "properties": {
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it for up to `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "minimum": 0
          },
          "poll_hint_s": {
            "type": "integer",
            "enum": [
              15,
              60
            ],
            "description": "15 while a run is open, a step is scheduled now or a command waits for its controller, else 60."
          },
          "day": {
            "$ref": "#/components/schemas/ControlDay"
          },
          "area": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "code",
              "name"
            ],
            "properties": {
              "code": {
                "type": "string"
              },
              "name": {
                "type": [
                  "string",
                  "null"
                ]
              }
            }
          },
          "controllers": {
            "type": "array",
            "maxItems": 50,
            "items": {
              "$ref": "#/components/schemas/ControlControllerToday"
            }
          },
          "truncated": {
            "type": "boolean",
            "description": "A cap left something out (50 controllers, 48 steps, the reads' row caps)."
          }
        },
        "description": "#363. The day of the irrigation controllers placed in one growing area.",
        "example": {
          "generated_at": "2026-10-22T07:32:05Z",
          "max_age_s": 10,
          "poll_hint_s": 15,
          "day": {
            "date": "2026-10-22",
            "starts_at": "2026-10-21T17:00:00Z",
            "time_zone": "Asia/Ho_Chi_Minh"
          },
          "area": {
            "code": "VN-LDG-VT03",
            "name": "Garden 3"
          },
          "controllers": [
            {
              "device_id": "ctl-03",
              "name": "Controller 3",
              "link": {
                "state": "online",
                "via": "gateway",
                "gateway": "gw-v3",
                "heard_at": "2026-10-22T07:31:50Z",
                "expected_s": 30,
                "ready": true
              },
              "hold_until": null,
              "program": {
                "state": "installed",
                "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                "program_version": 41,
                "control_program_id": 31,
                "valid_until": "2026-10-22T17:00:00Z",
                "withdrawable": true,
                "withdraw_effect": "stop_installed",
                "lease_version": 41,
                "lease_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
                "lease_control_program_id": 31,
                "withdrawal": null
              },
              "zones": [
                {
                  "zone": 3,
                  "name": "Rows 1-4",
                  "state": "running",
                  "source": "run_zone_reply",
                  "since": "2026-10-22T07:03:00Z",
                  "expected_end": "2026-10-22T07:23:00Z",
                  "reason": null,
                  "today": {
                    "applied_l": 840.0,
                    "planned_l": null,
                    "runs": 1
                  },
                  "moisture": {
                    "state": "no_band",
                    "value_pct": 28.4,
                    "obs_time": "2026-10-22T07:26:00Z",
                    "band": {
                      "lower_pct": null,
                      "upper_pct": null,
                      "sheet": null
                    }
                  }
                }
              ],
              "steps": [
                {
                  "zone": 3,
                  "start_s": 21600,
                  "duration_s": 1200,
                  "max_volume_l": 2625,
                  "planned_l": null,
                  "actual": {
                    "state": "done",
                    "litres": 1980.0,
                    "ended_at": "2026-10-21T23:20:40Z"
                  }
                }
              ],
              "commands": [
                {
                  "id": "9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f",
                  "name": "run_zone",
                  "status": "accepted",
                  "issued_by": "Lan",
                  "issued_at": "2026-10-22T07:02:10Z",
                  "params": {
                    "zone": 3,
                    "duration_s": 1200,
                    "max_volume_l": 2000
                  },
                  "expires_at": "2026-10-22T07:07:10Z",
                  "reason": null,
                  "measured": null
                }
              ]
            }
          ],
          "truncated": false
        }
      },
      "ControlControllerDay": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "generated_at",
          "max_age_s",
          "poll_hint_s",
          "day",
          "device_id",
          "name",
          "link",
          "hold_until",
          "program",
          "zones",
          "steps",
          "commands",
          "area",
          "limits",
          "truncated"
        ],
        "properties": {
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it for up to `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "minimum": 0
          },
          "poll_hint_s": {
            "type": "integer",
            "enum": [
              15,
              60
            ],
            "description": "15 while a run is open, a step is scheduled now or a command waits for its controller, else 60."
          },
          "day": {
            "$ref": "#/components/schemas/ControlDay"
          },
          "device_id": {
            "type": "string"
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "link": {
            "$ref": "#/components/schemas/ControlLink"
          },
          "hold_until": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time",
            "description": "#367 cross-review M2: the end of the controller's hold in force (a person withdrew today's program; the engine sends nothing automatic until then), or null."
          },
          "program": {
            "$ref": "#/components/schemas/ControlProgramToday"
          },
          "zones": {
            "type": "array",
            "maxItems": 16,
            "items": {
              "$ref": "#/components/schemas/ControlZoneToday"
            }
          },
          "steps": {
            "type": "array",
            "maxItems": 48,
            "items": {
              "$ref": "#/components/schemas/ControlStepToday"
            }
          },
          "commands": {
            "type": "array",
            "maxItems": 20,
            "items": {
              "$ref": "#/components/schemas/ControlCommandToday"
            }
          },
          "area": {
            "oneOf": [
              {
                "type": "null"
              },
              {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "code"
                ],
                "properties": {
                  "code": {
                    "type": "string"
                  }
                }
              }
            ]
          },
          "limits": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "duration_s_min",
              "duration_s_max",
              "max_volume_l_min",
              "max_volume_l_max",
              "max_expiry_s"
            ],
            "properties": {
              "duration_s_min": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "duration_s_max": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "max_volume_l_min": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "max_volume_l_max": {
                "type": [
                  "number",
                  "null"
                ]
              },
              "max_expiry_s": {
                "type": [
                  "integer",
                  "null"
                ]
              }
            },
            "description": "The controller profile's run_zone bounds (minima since #371): installation facts, never an irrigation amount."
          },
          "truncated": {
            "type": "boolean"
          }
        },
        "description": "#363. One irrigation controller's day.",
        "example": {
          "generated_at": "2026-10-22T07:32:05Z",
          "max_age_s": 10,
          "poll_hint_s": 15,
          "day": {
            "date": "2026-10-22",
            "starts_at": "2026-10-21T17:00:00Z",
            "time_zone": "Asia/Ho_Chi_Minh"
          },
          "device_id": "ctl-03",
          "name": "Controller 3",
          "link": {
            "state": "online",
            "via": "gateway",
            "gateway": "gw-v3",
            "heard_at": "2026-10-22T07:31:50Z",
            "expected_s": 30,
            "ready": true
          },
          "hold_until": null,
          "program": {
            "state": "installed",
            "command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
            "program_version": 41,
            "control_program_id": 31,
            "valid_until": "2026-10-22T17:00:00Z",
            "withdrawable": true,
            "withdraw_effect": "stop_installed",
            "lease_version": 41,
            "lease_command_id": "5b0f3c2e-8a51-4c1e-9d0a-3f7b2c1d4e5f",
            "lease_control_program_id": 31,
            "withdrawal": null
          },
          "zones": [
            {
              "zone": 3,
              "name": "Rows 1-4",
              "state": "running",
              "source": "run_zone_reply",
              "since": "2026-10-22T07:03:00Z",
              "expected_end": "2026-10-22T07:23:00Z",
              "reason": null,
              "today": {
                "applied_l": 840.0,
                "planned_l": null,
                "runs": 1
              },
              "moisture": {
                "state": "no_band",
                "value_pct": 28.4,
                "obs_time": "2026-10-22T07:26:00Z",
                "band": {
                  "lower_pct": null,
                  "upper_pct": null,
                  "sheet": null
                }
              },
              "nominal_flow_lpm": 100.0,
              "max_daily_l": 5000.0
            }
          ],
          "steps": [
            {
              "zone": 3,
              "start_s": 21600,
              "duration_s": 1200,
              "max_volume_l": 2625,
              "planned_l": null,
              "actual": {
                "state": "done",
                "litres": 1980.0,
                "ended_at": "2026-10-21T23:20:40Z"
              }
            }
          ],
          "commands": [
            {
              "id": "9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f",
              "name": "run_zone",
              "status": "accepted",
              "issued_by": "Lan",
              "issued_at": "2026-10-22T07:02:10Z",
              "params": {
                "zone": 3,
                "duration_s": 1200,
                "max_volume_l": 2000
              },
              "expires_at": "2026-10-22T07:07:10Z",
              "reason": null,
              "measured": null
            }
          ],
          "area": {
            "code": "VN-LDG-VT03"
          },
          "limits": {
            "duration_s_min": 1,
            "duration_s_max": 3600,
            "max_volume_l_min": 1,
            "max_volume_l_max": 20000,
            "max_expiry_s": 300
          },
          "truncated": false
        }
      },
      "ControlFleetAttention": {
        "description": "#363. What needs attention: exact counts of the open alarms the caller may read, and at most 20 items (alarms not shelved, urgent then warning then notice, the oldest first; then today's programs waiting for approval).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "alarms",
              "items",
              "capped"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "alarms": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "urgent",
                  "warning",
                  "notice",
                  "shelved"
                ],
                "properties": {
                  "urgent": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "warning": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "notice": {
                    "type": "integer",
                    "minimum": 0
                  },
                  "shelved": {
                    "type": "integer",
                    "minimum": 0
                  }
                }
              },
              "items": {
                "type": "array",
                "maxItems": 20,
                "items": {
                  "oneOf": [
                    {
                      "type": "object",
                      "additionalProperties": false,
                      "required": [
                        "type",
                        "id",
                        "kind",
                        "priority",
                        "state",
                        "since",
                        "subject",
                        "words_key",
                        "can_ack"
                      ],
                      "properties": {
                        "type": {
                          "const": "alarm"
                        },
                        "id": {
                          "type": "integer"
                        },
                        "kind": {
                          "type": "string"
                        },
                        "priority": {
                          "type": "string",
                          "enum": [
                            "urgent",
                            "warning",
                            "notice"
                          ]
                        },
                        "state": {
                          "type": "string",
                          "enum": [
                            "active_unacked",
                            "active_acked",
                            "cleared_unacked"
                          ]
                        },
                        "since": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "subject": {
                          "type": "object",
                          "additionalProperties": false,
                          "required": [
                            "area",
                            "device",
                            "zone"
                          ],
                          "properties": {
                            "area": {
                              "type": [
                                "string",
                                "null"
                              ]
                            },
                            "device": {
                              "type": [
                                "string",
                                "null"
                              ]
                            },
                            "zone": {
                              "type": [
                                "integer",
                                "null"
                              ]
                            }
                          }
                        },
                        "words_key": {
                          "type": [
                            "string",
                            "null"
                          ],
                          "description": "The reason token its facts name, worded by the console."
                        },
                        "can_ack": {
                          "type": "boolean",
                          "description": "Whether the caller may acknowledge it."
                        }
                      }
                    },
                    {
                      "type": "object",
                      "additionalProperties": false,
                      "required": [
                        "type",
                        "kind",
                        "program_id",
                        "device",
                        "since"
                      ],
                      "properties": {
                        "type": {
                          "const": "task"
                        },
                        "kind": {
                          "type": "string",
                          "enum": [
                            "program_waiting_approval"
                          ]
                        },
                        "program_id": {
                          "type": "integer"
                        },
                        "device": {
                          "type": "string"
                        },
                        "since": {
                          "type": "string",
                          "format": "date-time"
                        }
                      }
                    }
                  ]
                }
              },
              "capped": {
                "type": "boolean"
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "alarms": {
            "urgent": 0,
            "warning": 1,
            "notice": 0,
            "shelved": 1
          },
          "items": [
            {
              "type": "alarm",
              "id": 812,
              "kind": "command_refused_site",
              "priority": "warning",
              "state": "active_unacked",
              "since": "2026-10-21T22:12:00Z",
              "subject": {
                "area": "VN-LDG-VT03",
                "device": "ctl-03",
                "zone": 3
              },
              "words_key": "manual_override_active",
              "can_ack": true
            },
            {
              "type": "task",
              "kind": "program_waiting_approval",
              "program_id": 31,
              "device": "ctl-03",
              "since": "2026-10-21T17:05:00Z"
            }
          ],
          "capped": false
        }
      },
      "ControlFleetArea": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "code",
          "name",
          "controllers",
          "zones",
          "water_today",
          "sensors",
          "alarms"
        ],
        "properties": {
          "code": {
            "type": "string"
          },
          "name": {
            "type": [
              "string",
              "null"
            ]
          },
          "controllers": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "total",
              "online",
              "stale",
              "offline",
              "unknown"
            ],
            "properties": {
              "total": {
                "type": "integer",
                "minimum": 0
              },
              "online": {
                "type": "integer",
                "minimum": 0
              },
              "stale": {
                "type": "integer",
                "minimum": 0
              },
              "offline": {
                "type": "integer",
                "minimum": 0
              },
              "unknown": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "zones": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "total",
              "running",
              "scheduled_now"
            ],
            "properties": {
              "total": {
                "type": "integer",
                "minimum": 0
              },
              "running": {
                "type": "integer",
                "minimum": 0
              },
              "scheduled_now": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "water_today": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "applied_l",
              "planned_l",
              "plan",
              "reason"
            ],
            "properties": {
              "applied_l": {
                "type": "number",
                "minimum": 0
              },
              "planned_l": {
                "type": [
                  "number",
                  "null"
                ],
                "description": "Null whenever there is no plan, never 0."
              },
              "plan": {
                "type": "string",
                "enum": [
                  "rules",
                  "mixed",
                  "program_only",
                  "none",
                  "blocked"
                ],
                "description": "Where today's plan of the area comes from: `rules` (#243's rules issued every lease), `mixed` (some of its controllers' leases came from the rules and others did not: `planned_l` is then the planned litres of the rules' leases only), `program_only` (leases the rules did not issue: `planned_l` null), `blocked` (no lease from the rules and an enabled rule blocked: `reason`) or `none`."
              },
              "reason": {
                "type": [
                  "string",
                  "null"
                ],
                "description": "Why the rules are blocked (`plan: blocked`)."
              }
            }
          },
          "sensors": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "total",
              "stale"
            ],
            "properties": {
              "total": {
                "type": "integer",
                "minimum": 0
              },
              "stale": {
                "type": "integer",
                "minimum": 0
              }
            }
          },
          "alarms": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "urgent",
              "warning",
              "notice"
            ],
            "properties": {
              "urgent": {
                "type": "integer",
                "minimum": 0
              },
              "warning": {
                "type": "integer",
                "minimum": 0
              },
              "notice": {
                "type": "integer",
                "minimum": 0
              }
            }
          }
        },
        "description": "#363. A growing area holding an irrigation controller.",
        "example": {
          "code": "VN-LDG-VT03",
          "name": "Garden 3",
          "controllers": {
            "total": 1,
            "online": 1,
            "stale": 0,
            "offline": 0,
            "unknown": 0
          },
          "zones": {
            "total": 6,
            "running": 1,
            "scheduled_now": 0
          },
          "water_today": {
            "applied_l": 4120.0,
            "planned_l": null,
            "plan": "blocked",
            "reason": "no_signed_sheet"
          },
          "sensors": {
            "total": 4,
            "stale": 1
          },
          "alarms": {
            "urgent": 0,
            "warning": 1,
            "notice": 0
          }
        }
      },
      "ControlFleetAreas": {
        "description": "#363. The areas, at most 200 by code.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "items",
              "capped"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "items": {
                "type": "array",
                "maxItems": 200,
                "items": {
                  "$ref": "#/components/schemas/ControlFleetArea"
                }
              },
              "capped": {
                "type": "boolean"
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "items": [
            {
              "code": "VN-LDG-VT03",
              "name": "Garden 3",
              "controllers": {
                "total": 1,
                "online": 1,
                "stale": 0,
                "offline": 0,
                "unknown": 0
              },
              "zones": {
                "total": 6,
                "running": 1,
                "scheduled_now": 0
              },
              "water_today": {
                "applied_l": 4120.0,
                "planned_l": null,
                "plan": "blocked",
                "reason": "no_signed_sheet"
              },
              "sensors": {
                "total": 4,
                "stale": 1
              },
              "alarms": {
                "urgent": 0,
                "warning": 1,
                "notice": 0
              }
            }
          ],
          "capped": false
        }
      },
      "ControlFleetControllers": {
        "description": "#363. The controllers, at most 500 by device id.",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "running_or_outstanding",
              "items",
              "capped"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "running_or_outstanding": {
                "type": "boolean"
              },
              "items": {
                "type": "array",
                "maxItems": 500,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "device_id",
                    "name",
                    "area",
                    "link",
                    "lease"
                  ],
                  "properties": {
                    "device_id": {
                      "type": "string"
                    },
                    "name": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "area": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "link": {
                      "$ref": "#/components/schemas/ControlLink"
                    },
                    "lease": {
                      "oneOf": [
                        {
                          "type": "null"
                        },
                        {
                          "type": "object",
                          "additionalProperties": false,
                          "required": [
                            "program_version",
                            "valid_until"
                          ],
                          "properties": {
                            "program_version": {
                              "type": [
                                "integer",
                                "null"
                              ]
                            },
                            "valid_until": {
                              "type": [
                                "string",
                                "null"
                              ],
                              "format": "date-time"
                            }
                          }
                        }
                      ]
                    }
                  }
                }
              },
              "capped": {
                "type": "boolean"
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "running_or_outstanding": true,
          "items": [
            {
              "device_id": "ctl-03",
              "name": "Controller 3",
              "area": "VN-LDG-VT03",
              "link": {
                "state": "online",
                "via": "gateway",
                "gateway": "gw-v3",
                "heard_at": "2026-10-22T07:31:50Z",
                "expected_s": 30,
                "ready": true
              },
              "lease": {
                "program_version": 41,
                "valid_until": "2026-10-22T17:00:00Z"
              }
            }
          ],
          "capped": false
        }
      },
      "ControlFleetState": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "tenant",
          "generated_at",
          "max_age_s",
          "poll_hint_s",
          "day",
          "view",
          "attention",
          "areas",
          "controllers"
        ],
        "properties": {
          "tenant": {
            "type": "string"
          },
          "generated_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the answer was computed (the server serves it for up to `max_age_s`)."
          },
          "max_age_s": {
            "type": "integer",
            "minimum": 0
          },
          "poll_hint_s": {
            "type": "integer",
            "enum": [
              15,
              60
            ],
            "description": "15 while a run is open, a step is scheduled now or a command waits for its controller, else 60."
          },
          "day": {
            "$ref": "#/components/schemas/ControlDay"
          },
          "view": {
            "type": "string",
            "pattern": "^(admin|auditor|operator|agronomist:[0-9]+)$"
          },
          "attention": {
            "$ref": "#/components/schemas/ControlFleetAttention"
          },
          "areas": {
            "$ref": "#/components/schemas/ControlFleetAreas"
          },
          "controllers": {
            "$ref": "#/components/schemas/ControlFleetControllers"
          }
        },
        "description": "#363. The company's water today at a glance. Each section has `state`: `ok` with its figures, or `unavailable` (OverviewSectionUnavailable) when one of its reads failed.",
        "example": {
          "tenant": "coop-dl",
          "generated_at": "2026-10-22T07:32:05Z",
          "max_age_s": 10,
          "poll_hint_s": 15,
          "day": {
            "date": "2026-10-22",
            "starts_at": "2026-10-21T17:00:00Z",
            "time_zone": "Asia/Ho_Chi_Minh"
          },
          "view": "admin",
          "attention": {
            "state": "ok",
            "alarms": {
              "urgent": 0,
              "warning": 1,
              "notice": 0,
              "shelved": 1
            },
            "items": [
              {
                "type": "alarm",
                "id": 812,
                "kind": "command_refused_site",
                "priority": "warning",
                "state": "active_unacked",
                "since": "2026-10-21T22:12:00Z",
                "subject": {
                  "area": "VN-LDG-VT03",
                  "device": "ctl-03",
                  "zone": 3
                },
                "words_key": "manual_override_active",
                "can_ack": true
              },
              {
                "type": "task",
                "kind": "program_waiting_approval",
                "program_id": 31,
                "device": "ctl-03",
                "since": "2026-10-21T17:05:00Z"
              }
            ],
            "capped": false
          },
          "areas": {
            "state": "ok",
            "items": [
              {
                "code": "VN-LDG-VT03",
                "name": "Garden 3",
                "controllers": {
                  "total": 1,
                  "online": 1,
                  "stale": 0,
                  "offline": 0,
                  "unknown": 0
                },
                "zones": {
                  "total": 6,
                  "running": 1,
                  "scheduled_now": 0
                },
                "water_today": {
                  "applied_l": 4120.0,
                  "planned_l": null,
                  "plan": "blocked",
                  "reason": "no_signed_sheet"
                },
                "sensors": {
                  "total": 4,
                  "stale": 1
                },
                "alarms": {
                  "urgent": 0,
                  "warning": 1,
                  "notice": 0
                }
              }
            ],
            "capped": false
          },
          "controllers": {
            "state": "ok",
            "running_or_outstanding": true,
            "items": [
              {
                "device_id": "ctl-03",
                "name": "Controller 3",
                "area": "VN-LDG-VT03",
                "link": {
                  "state": "online",
                  "via": "gateway",
                  "gateway": "gw-v3",
                  "heard_at": "2026-10-22T07:31:50Z",
                  "expected_s": 30,
                  "ready": true
                },
                "lease": {
                  "program_version": 41,
                  "valid_until": "2026-10-22T17:00:00Z"
                }
              }
            ],
            "capped": false
          }
        }
      },
      "PlatformOverviewIrrigation": {
        "description": "#363. The irrigation fleet's health across companies (decision D10: no litres, no zone names).",
        "oneOf": [
          {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "state",
              "controllers",
              "online",
              "not_measured",
              "controllers_capped",
              "online_rate_7d",
              "rejects_14d",
              "expired_rate_14d",
              "commands_capped",
              "companies",
              "capped",
              "attention"
            ],
            "properties": {
              "state": {
                "const": "ok"
              },
              "controllers": {
                "type": "integer",
                "minimum": 0,
                "description": "Irrigation controllers in service."
              },
              "online": {
                "type": "integer",
                "minimum": 0
              },
              "not_measured": {
                "type": "integer",
                "minimum": 0,
                "description": "Connected directly: no heartbeat."
              },
              "controllers_capped": {
                "type": "boolean"
              },
              "online_rate_7d": {
                "type": "array",
                "minItems": 7,
                "maxItems": 7,
                "items": {
                  "type": [
                    "number",
                    "null"
                  ],
                  "minimum": 0,
                  "maximum": 1
                },
                "description": "Per farm-local day of the 7 before today, oldest first: the minutes the gateways serving the controllers were heard over their minutes."
              },
              "rejects_14d": {
                "type": "object",
                "additionalProperties": {
                  "type": "integer",
                  "minimum": 0
                },
                "description": "Refusals of run_zone and set_program within 14 days, by reason."
              },
              "expired_rate_14d": {
                "type": [
                  "number",
                  "null"
                ],
                "minimum": 0,
                "maximum": 1
              },
              "commands_capped": {
                "type": "boolean"
              },
              "companies": {
                "type": "array",
                "maxItems": 1000,
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "id",
                    "open_urgent",
                    "alarms_raised_7d"
                  ],
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "open_urgent": {
                      "type": "integer",
                      "minimum": 0
                    },
                    "alarms_raised_7d": {
                      "type": "integer",
                      "minimum": 0
                    }
                  }
                }
              },
              "capped": {
                "type": "boolean"
              },
              "attention": {
                "type": "array",
                "items": {
                  "type": "object",
                  "additionalProperties": false,
                  "required": [
                    "priority",
                    "kind",
                    "reason",
                    "count"
                  ],
                  "properties": {
                    "priority": {
                      "const": "urgent"
                    },
                    "kind": {
                      "const": "command_refused_security"
                    },
                    "reason": {
                      "type": "string",
                      "enum": [
                        "bad_sig",
                        "replayed",
                        "wrong_device"
                      ]
                    },
                    "count": {
                      "type": "integer",
                      "minimum": 1
                    }
                  }
                },
                "description": "One urgent line per security refusal reason seen within 14 days."
              }
            }
          },
          {
            "$ref": "#/components/schemas/OverviewSectionUnavailable"
          }
        ],
        "example": {
          "state": "ok",
          "controllers": 14,
          "online": 12,
          "not_measured": 1,
          "controllers_capped": false,
          "online_rate_7d": [
            0.98,
            0.97,
            0.99,
            0.99,
            0.96,
            0.98,
            0.99
          ],
          "rejects_14d": {
            "interlock": 1,
            "manual_override_active": 4
          },
          "expired_rate_14d": 0.02,
          "commands_capped": false,
          "companies": [
            {
              "id": "coop-dl",
              "open_urgent": 0,
              "alarms_raised_7d": 18
            }
          ],
          "capped": false,
          "attention": []
        }
      },
      "AlarmCounts": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "urgent",
          "warning",
          "notice",
          "shelved"
        ],
        "description": "#361: how many open alarms the caller may read, over every page: `urgent`, `warning` and `notice` count the ones not shelved, `shelved` the shelved ones of every priority.",
        "properties": {
          "urgent": {
            "type": "integer",
            "minimum": 0
          },
          "warning": {
            "type": "integer",
            "minimum": 0
          },
          "notice": {
            "type": "integer",
            "minimum": 0
          },
          "shelved": {
            "type": "integer",
            "minimum": 0
          }
        }
      }
    },
    "parameters": {
      "IdempotencyKey": {
        "name": "Idempotency-Key",
        "in": "header",
        "required": false,
        "description": "Makes a retry of this request safe (#169). A client-chosen key, 1 to 255 visible ASCII characters (a UUID is a good choice), scoped to the caller's tenant and principal (session user, API token or legacy token). The first request with a key runs; when it answers 2xx, that response (status, body and headers) is stored and replayed for 24 hours to every request with the same key and the same method, path, query and body bytes, marked `Idempotent-Replayed: true`, without running the operation again or writing another audit row. The same key with another request is 422 `idempotency_key_mismatch`; while the first request still runs it is 409 `idempotency_key_in_use` with `Retry-After`. A request that fails before its operation commits releases the key, so it may be sent again (corrected) with the same key. An operation that committed is never run again under its key, even when its response could not be recorded (a 500 after the commit; a server stop or a database error between the commit and the record): the retry is 409 `idempotency_key_in_use` for up to 5 minutes, then 409 `idempotency_key_used` until the key expires. A malformed or repeated header is 400 `invalid_idempotency_key`.",
        "schema": {
          "type": "string",
          "minLength": 1,
          "maxLength": 255,
          "pattern": "^[!-~]+$"
        },
        "example": "5b0f6c1e-9d7a-4c4e-8f3b-2a1d0e9c8b7a"
      }
    }
  },
  "webhooks": {
    "lot.sealed": {
      "post": {
        "operationId": "webhookLotSealed",
        "summary": "`lot.sealed` (sent to the partner)",
        "description": "Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "parameters": [
          {
            "name": "webhook-id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^evt_[0-9a-f]{32}$"
            },
            "example": "evt_6f1c2d3e4a5b46c7889900aabbccddee"
          },
          {
            "name": "webhook-timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "example": "1790000003"
          },
          {
            "name": "webhook-signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1,[A-Za-z0-9+/]{43}=$"
            },
            "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEventLotSealed"
              },
              "example": {
                "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                "type": "lot.sealed",
                "created_at": "2026-10-01T05:30:00.000Z",
                "tenant": "coop-dl",
                "data": {
                  "lot": "LO-260928-014",
                  "public_id": "9f86d081884c7d659a2feaa0c55ad015",
                  "facility": "VN-TGPH-021",
                  "sealed_at": "2026-09-28T10:15:00.000Z",
                  "manifest_sha256": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
                  "fruit_count": 128,
                  "event_count": 260
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received; the delivery is done."
          }
        }
      }
    },
    "lot.recalled": {
      "post": {
        "operationId": "webhookLotRecalled",
        "summary": "`lot.recalled` (sent to the partner)",
        "description": "Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "parameters": [
          {
            "name": "webhook-id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^evt_[0-9a-f]{32}$"
            },
            "example": "evt_6f1c2d3e4a5b46c7889900aabbccddee"
          },
          {
            "name": "webhook-timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "example": "1790000003"
          },
          {
            "name": "webhook-signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1,[A-Za-z0-9+/]{43}=$"
            },
            "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEventLotRecalled"
              },
              "example": {
                "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                "type": "lot.recalled",
                "created_at": "2026-10-01T05:30:00.000Z",
                "tenant": "coop-dl",
                "data": {
                  "lot": "LO-260928-014",
                  "public_id": "9f86d081884c7d659a2feaa0c55ad015",
                  "kind": "recall",
                  "reason": "contamination",
                  "scope": "consumer",
                  "recalled_at": "2026-10-02T03:00:00.000Z",
                  "cartons": 41,
                  "shipments": 1
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received; the delivery is done."
          }
        }
      }
    },
    "lot.withdrawn": {
      "post": {
        "operationId": "webhookLotWithdrawn",
        "summary": "`lot.withdrawn` (sent to the partner)",
        "description": "Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "parameters": [
          {
            "name": "webhook-id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^evt_[0-9a-f]{32}$"
            },
            "example": "evt_6f1c2d3e4a5b46c7889900aabbccddee"
          },
          {
            "name": "webhook-timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "example": "1790000003"
          },
          {
            "name": "webhook-signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1,[A-Za-z0-9+/]{43}=$"
            },
            "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEventLotWithdrawn"
              },
              "example": {
                "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                "type": "lot.withdrawn",
                "created_at": "2026-10-01T05:30:00.000Z",
                "tenant": "coop-dl",
                "data": {
                  "lot": "LO-260928-014",
                  "public_id": "9f86d081884c7d659a2feaa0c55ad015",
                  "kind": "withdrawal",
                  "reason": "contamination",
                  "scope": "consumer",
                  "recalled_at": "2026-10-02T03:00:00.000Z",
                  "cartons": 41,
                  "shipments": 1
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received; the delivery is done."
          }
        }
      }
    },
    "lab_result.recorded": {
      "post": {
        "operationId": "webhookLabResultRecorded",
        "summary": "`lab_result.recorded` (sent to the partner)",
        "description": "Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "parameters": [
          {
            "name": "webhook-id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^evt_[0-9a-f]{32}$"
            },
            "example": "evt_6f1c2d3e4a5b46c7889900aabbccddee"
          },
          {
            "name": "webhook-timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "example": "1790000003"
          },
          {
            "name": "webhook-signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1,[A-Za-z0-9+/]{43}=$"
            },
            "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEventLabResultRecorded"
              },
              "example": {
                "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                "type": "lab_result.recorded",
                "created_at": "2026-10-01T05:30:00.000Z",
                "tenant": "coop-dl",
                "data": {
                  "lot": "LO-260928-014",
                  "sampling_id": 12,
                  "lab": "LAB-VN-118",
                  "report_no": "KN-LO-260928-014",
                  "market": "CN",
                  "signed_at": "2026-09-29T02:00:00.000Z",
                  "passed": true
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received; the delivery is done."
          }
        }
      }
    },
    "shipment.departed": {
      "post": {
        "operationId": "webhookShipmentDeparted",
        "summary": "`shipment.departed` (sent to the partner)",
        "description": "Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "parameters": [
          {
            "name": "webhook-id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^evt_[0-9a-f]{32}$"
            },
            "example": "evt_6f1c2d3e4a5b46c7889900aabbccddee"
          },
          {
            "name": "webhook-timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "example": "1790000003"
          },
          {
            "name": "webhook-signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1,[A-Za-z0-9+/]{43}=$"
            },
            "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEventShipmentDeparted"
              },
              "example": {
                "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                "type": "shipment.departed",
                "created_at": "2026-10-01T05:30:00.000Z",
                "tenant": "coop-dl",
                "data": {
                  "shipment": "SH-LO-260928-014",
                  "facility": "VN-TGPH-021",
                  "container": "MSKU1234565",
                  "border_gate": "Hữu Nghị",
                  "destination": "CN",
                  "departed_at": "2026-09-29T09:00:00.000Z",
                  "lots": [
                    "LO-260928-014"
                  ]
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received; the delivery is done."
          }
        }
      }
    },
    "lot.trust_tier_changed": {
      "post": {
        "operationId": "webhookLotTrustTierChanged",
        "summary": "`lot.trust_tier_changed` (sent to the partner)",
        "description": "Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "parameters": [
          {
            "name": "webhook-id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^evt_[0-9a-f]{32}$"
            },
            "example": "evt_6f1c2d3e4a5b46c7889900aabbccddee"
          },
          {
            "name": "webhook-timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "example": "1790000003"
          },
          {
            "name": "webhook-signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1,[A-Za-z0-9+/]{43}=$"
            },
            "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEventLotTrustTierChanged"
              },
              "example": {
                "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                "type": "lot.trust_tier_changed",
                "created_at": "2026-10-01T05:30:00.000Z",
                "tenant": "coop-dl",
                "data": {
                  "lot": "LO-260928-014",
                  "public_id": "9f86d081884c7d659a2feaa0c55ad015",
                  "tier": "self_declared",
                  "previous_tier": "cross_checked",
                  "status": "on_hold",
                  "changed_at": "2026-10-01T05:30:00.000Z"
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received; the delivery is done."
          }
        }
      }
    },
    "report.filed": {
      "post": {
        "operationId": "webhookReportFiled",
        "summary": "`report.filed` (sent to the partner)",
        "description": "Every delivery is a POST of `application/json` to the subscription's URL with the Standard Webhooks headers `webhook-id` (the event id, the same on every attempt: deduplicate on it, delivery is at least once), `webhook-timestamp` (Unix seconds of this attempt) and `webhook-signature` (`v1,` + base64 of HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the secret after `whsec_`). Verify the signature over the raw body with a constant-time comparison and refuse a timestamp more than 300 seconds from your clock. Answer 2xx within 10 seconds; any other answer (a redirect is not followed) or none is a failed attempt, retried with exponential backoff (1 minute doubling, at most 6 hours) for 12 attempts (about 21 hours). 50 failed attempts in a row disable the subscription.",
        "tags": [
          "webhooks"
        ],
        "parameters": [
          {
            "name": "webhook-id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^evt_[0-9a-f]{32}$"
            },
            "example": "evt_6f1c2d3e4a5b46c7889900aabbccddee"
          },
          {
            "name": "webhook-timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "example": "1790000003"
          },
          {
            "name": "webhook-signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1,[A-Za-z0-9+/]{43}=$"
            },
            "example": "v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4="
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEventReportFiled"
              },
              "example": {
                "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
                "type": "report.filed",
                "created_at": "2026-10-01T05:30:00.000Z",
                "tenant": "coop-dl",
                "data": {
                  "report_id": 5,
                  "lot": "LO-260928-014",
                  "fruit": "Q-14-37",
                  "category": "ripeness_off",
                  "filed_at": "2026-10-01T05:29:58.000Z"
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Received; the delivery is done."
          }
        }
      }
    }
  }
}
