# API changelog

Changes to the HTTP API (`/v1/`, the OpenAPI document served at `/developers/openapi.json`), newest first. The rules for what may change in
v1 and how a route is retired are in [versioning.md](versioning.md). Each entry says whether it is additive or
breaking; a deprecation names its replacement and its sunset date.

## Unreleased

### The commune map's URL names its drawing version (#293, after #401)

Breaking for one `x-not-in-sdk` image URL only, accepted because no generated client calls it.

- `getPublicCommuneMap` is now `GET /v1/public/maps/{style}/{tileset}/{communes}/{osm_id}.svg`, `style` the drawing's
  version (`s2`, the brand indigo of #401). The image stays cached for a year as immutable; a change to how the map is
  drawn takes a new version, so it always comes with a new URL. An earlier version's URL answers 301 to the current
  one; a later or malformed version is the uniform 404. The records' `map.url` names the new path.
- `getPublicCommuneMapUnversioned`, the path #293 published (`/v1/public/maps/{tileset}/{communes}/{osm_id}.svg`, the
  first drawing), answers 301 to the map's current URL (cached as a public record is, never as immutable) instead of
  the image; a URL that names no stored map is still the uniform 404.

### The cockpit tells a hold, a withdrawal and a manual override as they are (#367/#363 cross-review)

Additive (every operation named is `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged).

- `getControlAreaToday` and `getControlControllerToday`: each controller gains `hold_until` (the end of the hold a
  person's withdrawal set, or null), and its `program` gains `withdrawal` {`requested_at`, `published`, `reason`}: the
  withdrawal of the controller's program asked for since its lease was accepted, whether the platform published it,
  and the person's reason (null to an agronomist), or null. `withdraw_effect` may be `already_held` (the controller is
  held and nothing else is in force; a withdrawal answers 202 again). A step of the lease due after its withdrawal is
  `withdrawn` (`actual.state`), never `pending` or `missed`. The day's program and lease include a person's
  set_program issued yesterday whose lease still runs.
- `withdrawDeviceProgram`: a controller already held, with nothing else in force, is withdrawn again with 202 (the hold
  kept) rather than 409 `no_program`.
- Alarms: a controller held by a withdrawal raises no `step_missed`; a rule blocked only by the manual override
  (`manual_override`) raises no `rule_blocked` and keeps its zone's band; `moisture_outside_band` counts as planned
  only a step still to come or done, none of a withdrawn lease and nothing while the controller is held.

### One program in force for the budget, the zone history and the engine (2026-10-23 cross-feature review)

Additive in shape; the values follow one rule now (control/in_force.py).

- `listControlBudget`: `plan` takes `replaced` (a person's own set_program replaced the engine's program: no planned
  water) and `refused` (every program of the day that became a command was refused or failed: no planned water) beside
  `dispatched` and `withdrawn`; `withdrawn` now also when a withdrawal of the controller's program was asked for after
  the program's dispatch or the controller reported it replaced or cancelled. `planned_mm` and `applied_mm` are litres
  over the zone's irrigated area before efficiency, the zone history's basis (before: the depth at the roots, and
  applied litres times efficiency).
- `getControlZoneHistory`: `planned_l` follows the same rule; `et0_mm`, `et0_status` (`ok`, `needs_krs`, `refused`),
  `kc_stage` and `rain_mm` are filled from the zone's weather station's latest stored day and the next day's program.
- `approveControlProgram`: 409 `manual_override_active` while a person's own program is in force on the controller and
  its rules were not resumed; the proposal is then superseded. A dispatch checks the same again before it is sent.

### Irrigation control: salinity, the control home and the advisory view (#354, wave 4 of #243)

Additive (both new operations are `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged). Both take
a signed-in session only; no API token or API client reaches them.

- `getControlHome` (`GET /v1/control/home`, CONTROL_READ, operators narrowed to their facilities' controllers, an
  agronomist to what rests on a sheet they signed): the controllers in scope, the programs waiting for a person's
  approval, the rules by state (`ok`, `blocked`, `fallback`, and `not_ready`: a disabled rule whose sheet would not let
  it be enabled today, with that reason, e.g. `no_signed_sheet`), the open salinity alerts and each weather station's
  latest reference ET0 day (`et0_mm` null on a `needs_krs` day).
- `getControlAdvisory` (`GET /v1/control/advisory`, AGRONOMY_SHEET_READ): per signed sheet in force today its lime
  and fertiliser advice exactly as signed (texts in vi, en and zh-Hans, the attachment's SHA-256, `requires_lab_test`),
  its references, its signer and the company's growing areas of its crop (`[]` for a caller holding no role that reads
  growing areas, an agronomist alone); `drafts` counts the sheets not signed yet, and `withheld` the signed sheets in
  force not listed because their stored document no longer hashes to what was signed or their signer is no longer
  verified. No amount and no formula: the amounts come from the lab test.
- `ControlRule` (every rule answer): a new member `sheet_gate`, the reason the rule's sheet would block it today
  (`no_signed_sheet`, `sheet_expired`, `sheet_incomplete`, ...) or null when the sheet is usable, enabled or not.
- Salinity: a zone watered from a sheet with a `salinity` section is checked on every compose against usable EC
  readings (`water.ec` of the controller and the zone's probes, `soil.ec_bulk` or `soil.ec_pore` of the probes at their
  depths; mS/cm only, never g/L). A program's `provenance` zones (`getControlProgram`, `previewControlRule`) gain
  `salinity` (`ok`, `exceeded` or `not_measured`, per side the limit, the highest usable value and every source); a
  zone above a limit whose sheet says `block` is `blocked` with reason `salinity_block` (a rule's `state_reason` may
  read `salinity_block`), and the engine raises the alerts `salinity_block` (high) and `salinity_alert` (warning),
  each listing every zone it found (`zones`). A zone a fallback waters is checked against both rules' sheets, the
  strictest binding (`salinity_sheets`); a blocked zone stays blocked while its EC reads `not_measured`.
- The engine stores the reference ET0 day of every zone's weather station by itself (no rule needed), so
  `listControlEt0Days` lists those days for up to 92 days back (a `refused` day once it ended 2 days ago).

### A zone's bound sheet in the cockpit's day answers (#373, CP-10 of #357)

Additive (the operations are `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged).

- `getControlAreaToday` and `getControlControllerToday`: each zone gains `sheet` (optional in the schema, always
  sent), the agronomy sheet the zone's enabled rule is bound to, whatever today's band or the rule's state:
  `{id, status, version, stage, stage_name}` or null when no enabled rule binds one. `status` is `signed` only while
  today is within the sheet's validity, `expired` past its last valid day, `not_yet_valid` before its first, else the
  sheet's own (`draft`, `superseded`, `revoked`); `stage` and `stage_name` (`{vi, en, zh-Hans}`) are the stage covering
  today, else null. It is read in the statement that already reads the bands' sheets (no statement added).

### The cockpit's controller day names the program held and what a withdrawal would do (#371)

Additive (both operations are `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged).

- `getControlAreaToday` and `getControlControllerToday`: each controller's `program` gains `lease_version`,
  `lease_command_id` and `lease_control_program_id`, the program the controller holds now (its lease in force; all
  null when none is installed), which the day's newest set_program may not be; and `withdraw_effect`
  (`stop_installed`, `stop_sending`, `hold` or null). `withdrawable` now says whether
  `POST /v1/devices/{id}/program-withdrawal` would be accepted (a lease in force, a set_program waiting for the
  controller, or a rule or proposal to hold), no longer only whether a lease is in force.
- `getControlControllerToday`: `limits` gains `duration_s_min` and `max_volume_l_min`, the profile's run_zone minima.

### The command log's filters (#372, CP-9 of #357)

Additive (the new parameters are `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged).

- `listDeviceCommands` (`GET /v1/devices/{id}/commands`) takes `name` (a command name: `run_zone`, `set_program`,
  `calibrate`...), `status` (one command state) and `from` / `to` (farm-local dates, Asia/Ho_Chi_Minh, both included),
  each optional, with the same cursor (an empty value is no filter); 400 `bad_name`, `bad_status`, `bad_from`, `bad_to`
  (a year outside 2000 to 9998 too), and `bad_range` when `to` is before `from`. Each read starts from the device's
  indexes (`commands_device`, `commands_device_outcome`), never a scan of the commands.
- `getControlZoneHistory` gains `moisture`: the soil moisture of the zone's own probes, one series per probe depth (the
  basis depth first), hourly up to 14 days, else per farm day; null when the zone names no probe. It is read under the
  zone's scope, so an agronomist reads it for the zones whose rules cite their sheets.

### Withdraw today's program from the app (#367, CP-6 of the cockpit epic #357)

Additive (the new operation is `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged). It takes a
signed-in session only; no API token or API client reaches it.

- `withdrawDeviceProgram` (`POST /v1/devices/{id}/program-withdrawal`, `{reason, control_program_id?}`): withdraws the
  program a controller holds now through the command channel's durable withdrawal (no new command is sent; a run
  started by hand keeps running) and holds the control engine for the controller until the next farm-local midnight.
  202 `{withdrawal: {owed_at, published}, control_program: {id, status, program_version} | null, hold_until}`, times
  RFC 3339 UTC, whenever the withdrawal was recorded (`published` false while it is still owed); the programs composed
  before it that never went out are superseded; 409 `no_program` when there is nothing to stop, supersede or hold (no
  program on the controller, none waiting, no rule); 404 for a device of another company or outside an operator's
  facilities. The reason refuses control and format characters. The company's admins, and its operators for the controllers of their facilities
  (the new session-only policy `program_withdraw`); a reason is required, no step-up. Audited
  (`device.program.withdraw`, with the reason). The answer never waits for the broker: the controller's reports (the
  program's final reply `aborted: cancelled`) say the program stopped.
- `releaseDeviceProgramHold` (`POST /v1/devices/{id}/program-hold/release`, `{}`): ends a controller's hold before
  its end and makes its enabled rules due, so the engine composes it again (a proposal under required approval, a
  dispatch under automatic approval). The same people as the withdrawal (the session-only policy
  `program_hold_release`), with step-up; 200 `{released: {hold_until, released_at}, rules_due}`; 409 `not_held`; 404 as
  above. Audited (`device.program.hold_release`).
- `ControlProgram.status` and `ControlProgramSummary.status` (and the `status` filter of `listControlPrograms`) gain
  `withdrawn`; `ControlProgram` gains `withdrawal` (`{by, at, reason}` or null; `at` RFC 3339; `by` null to an
  agronomist; `reason` `[removed]` once the company has left).
- `ControlRule` gains `hold_until` (RFC 3339, null when its controller is not held or the hold has ended): while it is
  to come, the engine proposes and sends nothing automatic for the rule's controller; a person may still approve a
  program by hand.

### Cockpit history reads: farm days, zone history and sensor health (#365, CP-5 of #357)

Additive (the new operations are `x-not-in-sdk`, and so is `getSensorSeries`, so the partner SDK clients' generated
code is unchanged). Both new operations take a signed-in session only.

- `getSensorSeries` (`GET /v1/growing-areas/{code}/sensor-series`): `grain=local_daily`, the merge of the 24 hourly
  summaries of each Asia/Ho_Chi_Minh day (exact over the whole history); `bucket_start` is the day's local midnight,
  the range at most 366 days (400 `range_too_long`), and the answer adds `time_zone` and `day_starts_at`. The `hourly`
  and `daily` (UTC) grains are unchanged; `bad_grain` now names the three grains.
- `getControlZoneHistory` (`GET /v1/control/zones/{device}/{zone}/history?from=&to=`): a zone's planned and delivered
  litres (and mm) per farm day, how the day's program decided it, its runs and the moisture bands of its signed
  sheets; at most 92 days. The ET0 columns are null until the FAO-56 water balance (#353) records them.
- `getControlSensorHealth` (`GET /v1/control/sensor-health?area=`): a growing area's probes with their link (the
  health gate's freshness rule), hourly coverage and QC counts over 30 days, the rules that read them and today's gate
  decisions.

### Irrigation control: ET0 water balance rules (#353, wave 3 of #243)

Additive (every new operation is `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged). Every
operation takes a signed-in session only; no API token or API client reaches them.

- `listControlEt0Days` (`GET /v1/control/et0`, `?device=`, `?from=`, `?to=` local dates, at most 92 days, 400
  `invalid_from`, `invalid_to`, `invalid_span`): the weather stations' local days with their FAO-56 Penman-Monteith
  reference ET0 (`status` `ok`, `needs_krs` when radiation was not measured, `refused` with its `reason`), every input,
  how it was found and whether it is estimated (`estimated`), and the equations' trace.
- `listControlBudget` (`GET /v1/control/budget`, the same parameters): per zone and local date what the day's last
  program sent planned (`plan`, `planned_mm`, `planned_l`, `clamps`, an ET0 zone's `et0` trace) and what the
  controller reported delivered (`applied_l`, `applied_mm`); null where the source holds nothing.
- `ControlZone`, `createControlZone`, `updateControlZone`: two optional members, `field_capacity_pct` and
  `wilting_point_pct` (volumetric %, given together, the wilting point below field capacity, else 400
  `invalid_water_holding`): the zone soil's water-holding facts the ET0 rule's root-zone bucket needs.
- `et0_budget` rules are enabled now (`enableControlRule`): they need a fallback schedule rule, a weather station on
  every zone (409 `station_missing`) and, when given, both gate parameters (409 `gate_parameters_incomplete`); only a
  `lighting` rule still answers 409 `kind_not_available`. `fallback_rule_id` is accepted on an et0_budget rule.
- A program's `provenance` (`getControlProgram`, `previewControlRule`) gains `budget` (per zone the planned depth and
  litres, the clamps and an ET0 zone's trace) and `et0` (the weather stations' ET0 days the program cites).
- `ControlEt0Day` carries `seq`, the version of the station day (the latest is listed; programs cite the one they
  used), and the reasons `light_suspect` and `radiation_above_clear_sky`; `truncated` on both pages is true whenever any
  cap behind the answer was reached; `from` and `to` take the years 2000 to 2100 (else 400).

### The irrigation cockpit's live answers (#363, CP-4 of #357)

Additive (every new operation is `x-not-in-sdk`, and the platform overview is not in the partner SDK clients, so their
generated code is unchanged). Every operation takes a signed-in session only, answers `Cache-Control: no-store`, is
served from a 10-second server cache (`max_age_s`) and carries the farm-local day (`day {date, starts_at,
time_zone}`) and a poll hint (`poll_hint_s`: 15 while a run is open, a step is scheduled now or a command waits for
its controller, else 60). Shapes: the irrigation cockpit plan's §2.7.

- `getControlFleetState` (`GET /v1/control/fleet-state`): the company's attention list (alarm counts by priority and
  shelved, at most 20 items: alarms in priority order, then today's programs waiting for approval), its growing areas
  holding an irrigation controller (links, zones running or scheduled now, today's water against the rules' plan,
  `plan` `rules`, `mixed`, `program_only`, `blocked` or `none`, `planned_l` null whenever there is no plan, stale probes, alarms) and its controllers (link and lease).
- `getControlAreaToday` (`GET /v1/control/areas/{code}/today`) and `getControlControllerToday`
  (`GET /v1/control/controllers/{id}/today`): each controller's link, today's program, its zones (state from the
  controller's reports only: a request is `requested`, never `running`; soil moisture against the signed sheet's
  band, every band value null without one), its lease's steps with what was observed of each, and its 20 newest
  commands (`issued_by` a display name, null for an agronomist, who also reads a program's steps of their zones only);
  a controller's answer adds its run_zone limits and its zones' nominal flow and daily cap. A foreign, missing or
  out-of-scope area or controller answers 404, as a company that does not exist does on all three answers.
- `listAlarms` and `getAlarm` are now read under the control read policy: an agronomist of the company reads, of the
  controllers of the rules bound to a sheet they signed, the controller-level alarms and those of their rules' zones,
  of their rules and of the probes those zones name (before: 403), without the people who acknowledged or shelved them
  (`acked.by`, `shelved.by`, their notes and `events[].actor` are now nullable, null for them); acknowledging and
  shelving stay refused to them (403). The alarm catalog gains `sheet_hash_mismatch`, `step_missed`, `rule_blocked`,
  `salinity_block`, `rule_on_fallback`, `probe_stale_in_use` and `moisture_outside_band` (`AlarmView.kind` is a
  token a client words; `subject.type` `rule` is now used), and a program step's 0 litres or litres over its limit
  raise `run_no_water` and `delivered_over_limit` as a run's do. An alarm of a #243 cause links its alert
  (`source_alert_id`), which the hourly digest mails instead.
- `getPlatformOverview` gains the section `irrigation` (optional in the schema, always sent): controllers in service,
  online and not measured, the gateways' heard rate per farm-local day of the last 7, refusals by reason and the
  expired rate over 14 days, each company's open urgent alarms and alarms raised in 7 days, and one urgent line per
  security refusal reason; never litres or zone names.

### Irrigation control: zones, rules and programs (#352, wave 2 of #243)

Additive (every new operation is `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged). Every
operation takes a signed-in session only; no API token or API client reaches them.

- `listControlZones`, `createControlZone`, `updateControlZone`, `deleteControlZone` (`/v1/control/zones`): the zones
  of the company's irrigation controllers and their installation facts.
- `listControlRules`, `createControlRule`, `getControlRule`, `updateControlRule`, `enableControlRule` (step-up),
  `disableControlRule`, `setControlRuleApproval` (step-up), `previewControlRule` (`/v1/control/rules`): schedule and
  threshold rules bound to a signed agronomic input sheet; `et0_budget` and `lighting` rules are recorded but answer
  409 `kind_not_available` when enabled.
- `resumeControlRule` (`POST /v1/control/rules/{id}/resume`, step-up): while a person's own set_program
  (`createDeviceCommand`) is in force on a controller, its rules are `blocked` with reason `manual_override` and the
  control engine sends it nothing; an admin resumes them over that program (409 `no_override` when none is in force).
  `ControlRule.resumed_command_id` names the person's command they were resumed over.
- `listControlPrograms`, `getControlProgram`, `approveControlProgram`, `rejectControlProgram`
  (`/v1/control/programs`): the programs the control engine composes, approved by a person with a recent
  second-factor proof (401 `mfa_step_up_required`; 409 `program_changed`
  when its decisions changed since it was proposed) and dispatched as a signed set_program through the device command
  channel, with a program version CropPath assigns. `createDeviceCommand` is unchanged: a caller's set_program still
  names its own `program_version`.
- The company data export (`downloadCompanyExport`) gains `control_zones.csv`, `control_rules.csv` and
  `control_programs.csv` ([company-export.md](company-export.md)); people are named `user-<account id>` there.
- `getAgronomyHome`: `today.state` is now `available`, with the programs composed today that cite a sheet the caller
  signed (`programs`) and the rules bound to one whose zones are on their fallback schedule (`fallback_zones`).

### Alarms of the irrigation cockpit (#361, CP-3 of #357)

Additive (every new operation is `x-not-in-sdk`, and the new notification kind and its parameters are behind
`x-sdk-enum` and `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged). The alarms follow one
model: a catalog of kinds, each with a priority and a response.

- `listAlarms` (`GET /v1/alarms`, `state=open|closed`, `priority`, `area`, `device`, `cursor`, `limit` 1 to 100) and
  `getAlarm` (`GET /v1/alarms/{id}`, with the alarm's history): the selected company's alarms, for its admins and
  auditors and its operators within their facilities (an alarm outside them, or another company's, answers 404
  `not_found`). Agronomists and lab users are refused (403).
- `acknowledgeAlarm`, `shelveAlarm` and `unshelveAlarm` (`POST /v1/alarms/{id}/ack|shelve|unshelve`): for the
  company's admins and its operators within their facilities; auditors are refused (403). Acknowledging or unshelving
  again answers 200 unchanged. A shelve takes `until` (an RFC 3339 date-time with its offset) at most 12 hours ahead
  for an urgent alarm and 72 hours for a warning or a notice (400 `shelve_too_long` past it) and a `reason` from a
  list with an optional note (400 `bad_until`, `bad_reason`, `bad_note`); a closed alarm is not shelved (409
  `alarm_closed`). Each write is audited (`alarm.ack`, `alarm.shelve`, `alarm.unshelve`) and takes an
  Idempotency-Key.
- Every alarm route takes a signed-in session only (`x-session-only`) and answers `Cache-Control: no-store`.
- A new notification kind, `alarm_raised` (`NotificationKind`, with `alarm_id`, `alarm_kind`, `priority`, `device`,
  `zone` and `area` in `NotificationParams`), for the company's admins on urgent and warning alarms, once per
  occurrence (the operators of the alarm's facility get the email only). The hourly alert email digest also counts
  the company's new urgent alarms, each once (an alarm linked to an alert is counted through its alert only).
- The company data export (`downloadCompanyExport`) gains two files, `alarms.csv` and `alarm_events.csv`
  ([company-export.md](company-export.md)); no other file or column changes.

### Agronomists and signed agronomic input sheets (#351, wave 1 of #243)

Additive (every new operation, parameter and member is `x-not-in-sdk` or behind `x-sdk-enum`, so the partner SDK
clients' generated code is unchanged). Nothing automates anything yet: no rule, program or command reads a sheet.

- A new company role, `agronomist`, invited by the company's admin (`createInvitation`, `role: agronomist`) and listed
  with the members (`Member.role`, `Invitation.role`, `AccountLinkInfo.role`, `NotificationParams.role`,
  `PersonalData.roles`; the SDK clients keep the released lists, `x-sdk-enum`). It is never delegated: no API token
  or API client holds it, and every agronomy operation takes a signed-in session only. An agronomist's account is
  CropPath's to reset, unlock or sign out, as a lab user's is, and stays so once it has an agronomist registry row or
  a signature, whatever role it holds later (409 `reset_by_support`, `unlock_by_support`, `sign_out_by_support`).
  Only an invitation gives the role: `updateMember` (`PATCH /v1/members/{user_id}`) answers 409
  `agronomist_by_invitation` for a change to the role or for a member who holds it.
- `listAgronomists`, `createAgronomist`, `getAgronomist`, `verifyAgronomist`, `suspendAgronomist`
  (`/v1/agronomists`): the platform's agronomist registry (platform admins; an agronomist reads their own row).
  Verifying takes a second platform admin: the one who registered the row, the row's own account, or the one whose
  reset of the account's two-step sign-in sent the row back to `pending`, is answered 409 `four_eyes_required`.
- `resetMemberTwoFactor` (`POST /v1/members/{user_id}/two-factor/reset`, a platform admin's reset: the only one an
  agronomist's account gets) also sends the account's `verified` agronomist registry row back to `pending` in the
  same transaction, with who reset it, when and why in its `suspended_by`, `suspended_at` and `suspend_reason`, and
  `agronomist_id` and `agronomist_status` in the reset's audit row; another platform admin, never the one who did the
  reset, verifies it again before the person signs. The response is unchanged.
- `listAgronomySheets`, `createAgronomySheet`, `getAgronomySheet`, `updateAgronomySheet` (`If-Match`, a strong tag
  only: a weak `W/` tag is 412; 428 without one),
  `getAgronomySheetDocument`, `signAgronomySheet`, `revokeAgronomySheet`, `copyAgronomySheet`
  (`/v1/agronomy-sheets`): the company's agronomic input sheets (`agritrace.agronomy-sheet/1`) and their in-app
  signatures.
- `getAgronomyHome` (`GET /v1/agronomy/home`): the agronomist's home.
- The company data export (`downloadCompanyExport`) gains two files, `agronomy_sheets.csv` and
  `agronomy_sheet_attestations.csv` ([company-export.md](company-export.md)); no other file or column changes.
- `agronomist=1` on `getMyPersonalData` (`GET /v1/account/personal-data`): adds `agronomist`, the caller's registry
  row (null without one); `0` or no parameter answers exactly as before; any other value is 400 `bad_agronomist`.

### The command channel to irrigation controllers (#242)

Additive in shape (every new member, parameter, status value and response is `x-not-in-sdk` or behind `x-sdk-enum`,
so the partner SDK clients' generated code is unchanged), with one behaviour change for every command: a command is
issued only to an approved device that an active, approved key reaches, its own or that of an approved gateway at its
site. A client that reads the error's `code` sees the new codes below.

- Every command (`issueDeviceCommand`, `POST /v1/devices/{id}/commands`, and the set_session commands a measurement
  session sends): a device the platform has not approved, or that no active approved key reaches, is refused with 409
  `device_not_approved`. Normally nothing is recorded and the Idempotency-Key is released, so a retry with the same key
  runs again; but a `set_program` whose device is refused by the second approval check, just before its program is
  published, is recorded as a failed command and its Idempotency-Key stays used.
- Actuation commands (an irrigation controller's `run_zone`, a timed zone run, and `set_program`, a program lease):
  sent as a command document signed with the platform command key, which the controller verifies and enforces
  locally; every param the profile declares must be given within its declared range. Without a platform command key
  the server refuses every actuation command with 503 `command_signing_unavailable` (nothing recorded, the
  Idempotency-Key not used up); config commands are not affected. A facility-scoped operator may issue `calibrate`,
  `run_zone` and `set_program` to a device of its facilities.
- `set_program`: its `program_version` must be above the highest `program_version` of every `set_program` already
  issued to the device, at any site and whatever became of it (a failed one included), because the controllers rely
  on strictly rising program versions. An equal or lower one is refused with 409 `program_version_not_increasing`;
  nothing is recorded and the Idempotency-Key is released, so a retry with a higher version and the same key runs.
- `Command.status` (`getCommand`, `listDeviceCommands`): an actuation command moves `pending`, `sent`, then `accepted`
  and `completed` or `aborted`, or `rejected`, or `expired` (not delivered or accepted before its expiry, or no final
  report came); `failed` when the dispatch failed. These five new values are answered with or without `channel=1`.
  The SDK clients keep the released list (`pending`, `sent`, `succeeded`, `failed`, `x-sdk-enum`).
- `channel=1` on `getCommand` (`GET /v1/commands/{id}`) and `listDeviceCommands` (`GET /v1/devices/{id}/commands`):
  each command also has `kind` (`config` or `actuation`), `expires_at`, `reason` (why an actuation command was
  rejected, aborted or expired, for example `bad_sig`, `interlock` or `no_final_report`) and `accepted_at`. `0` or no
  parameter answers exactly the members answered before; any other value is 400 `bad_channel`. The signed document is
  never answered.
- `listCommandKeys` (`GET /v1/command-keys`): the public part of the platform command key (`kid`, `alg` ES256, `jwk`),
  at most one key today, an empty `keys` list when the server has none. A controller is provisioned with it to verify
  the commands it receives. Allowed for company admins, platform admins and operators (a session or an operator API
  client), as issuing a command; auditors and labs are refused; not audited.
- `DeviceCreate.profile`: the irrigation controller's profile `vn.agritrace.irrigation-controller` (its commands
  `run_zone` and `set_program`) is served at /developers/downloads/profiles/irrigation-controller.json.
- Capabilities vocabulary 1.4.0 (`/developers/downloads/capabilities-v1.json`), additive: what an irrigation controller
  reports, `valve.state` (`open` or `closed`, the zone in `meta.zone`), `pump.state` (`on` or `off`), `light.level`
  (a grow light's output, 0 to 100 %), `water.volume_delivered` (litres a zone run delivered, the zone in
  `meta.zone`) and `dose.volume` (litres a dosing pump delivered in a run). The irrigation controller's profile
  declares them as the readings it produces.
- set_session outcomes (`SessionCommand.reason` of `openMeasurementSession` and `allocateFruit`,
  `FruitActionCommand.reason` of an `actOnFruit` re-measure): a new reason `device_not_approved` (status `refused`)
  for a device the platform has not approved or that no active approved key reaches. The SDK clients keep the
  released list (`x-sdk-enum`).
- Upgrade (migration 114): the new `commands` columns (`kind`, `document`, `expires_at`, `accepted_at`, `reason`) and
  the table `command_replies`. Existing commands are config commands and keep their status.

### A lab serves only the companies linked to it (#278)

Additive: three new operations of the platform admin console (all `x-not-in-sdk`, with their schemas `LabCompany` and
`LabCompanyList`, so the partner SDK clients' generated code is unchanged), and a new 409 code of `sampleLot` for a
client that reads the error's `code`.

- `sampleLot` (`POST /v1/lots/{lot}/samples`) draws the lab only among the labs in force with an active key that serve
  the lot's company, so a demonstration lab is never drawn for a real company's lot, nor a real lab for a
  demonstration lot. A lab serves no company until a platform admin links one. When no such lab serves the company the
  lot is not sampled: 409 `no_lab_serves_this_company` (409 `no_accredited_lab_available` stays the answer when no lab
  is in force at all, whatever the market). The D15 approved-lab draw (`no_approved_lab_available`) considers only the
  labs serving the company. The partner SDK clients keep the operation's released description (`x-sdk-description`)
  and 409 object (`x-sdk-object`).
- `listLabCompanies` (`GET /v1/labs/{code}/companies`): the companies the lab serves, at most 500.
- `linkLabCompany` (`PUT /v1/labs/{code}/companies/{tenant}`): no body; 201 for a new link, 200 when the lab already
  served the company (nothing changes). The lab logins' company record (`croppath-labs`) is refused (409
  `lab_logins_company`); past 500 companies, 409 `too_many_companies`. Audited `lab_company.link`.
- `unlinkLabCompany` (`DELETE /v1/labs/{code}/companies/{tenant}`): 204; the samplings already made keep their lab; a
  lab that does not serve the company is a 404. Audited `lab_company.unlink`.
- Platform admins only (a session or an API token): no company role and no lab user reads or changes the links, so a
  company never learns which other companies a lab serves.
- Upgrade (migration 113): each lab is linked to every company it already sampled for, except a demonstration lab with
  a company that is not a demonstration company, so existing use keeps its lab. The demo scenario and the
  demonstration company's history link their labs to the company they run for.

### A facility's packing-house certifications (#269)

Additive: three new operations of the console (all `x-not-in-sdk`, so the partner SDK clients' generated code is
unchanged). ISO 22000, FSSC 22000, BRCGS and IFS certify a packing house, not a farm (owner decision on #156), so they
are recorded on the facility. They are shown to the company's staff only: no trust tier and no public page uses them.

- `listFacilityCertifications` (`GET /v1/facilities/{code}/certifications`): every certification of the facility (at
  most 100, one page), each with its status today (`valid`, `expired`, `not_yet_valid`, `ended`). Same roles as
  reading the facility; an operator reads only its own facilities.
- `createFacilityCertification` (`POST /v1/facilities/{code}/certifications`): the scheme, the certificate number, the
  certifier, the validity and the SHA-256 of the certificate the company uploaded first with
  `PUT /v1/attachments/{sha256}` (never public; the facility's readers read it through `GET /v1/attachments/{sha256}`,
  an operator now also the certificates of its facilities' certifications). The same scheme and number are recorded
  once per facility (409 `certification_already_recorded`). A facility proposal takes none until CropPath approves it
  (409 `facility_not_approved`, as for its GLN). Company admins. Audited `facility.certification.create`.
- `endFacilityCertification` (`POST /v1/facilities/{code}/certifications/{id}/end`): ends a certification from a day
  within its validity, with a reason; once (409 `certification_already_ended`). Audited `facility.certification.end`.
- Growing-area certifications of these schemes (`createCertification`, `POST /v1/growing-areas/{code}/certifications`):
  still accepted with the same answer, so released clients keep working, but one recorded from this change on is
  stored unverified whatever it holds: it never counts towards a lot's trust tier or shows on a public page, and
  recording it again cannot verify it (409 `certification_already_recorded`). Record them on the facility instead.
  Certifications recorded before this change are judged as before (no tier changes). The console no longer offers
  these schemes on a growing area.

### A growing-area certification's verification (#269)

Additive, on request only: `listCertifications` (`GET /v1/growing-areas/{code}/certifications`) takes `verified=1`,
which adds each certification's `verified`, whether the server counts it as verified (the rule of the Certification
schema, including the packing-house schemes recorded on a growing area since the change above). The console shows it
instead of repeating the rule. Without the parameter (or with `0`) the answer is exactly as before, so a client
generated from an earlier document, whose Certification is closed, never receives the field; any other value is
refused (400 `bad_verified`). The parameter and the field are `x-not-in-sdk`: the partner SDK clients are unchanged.
`createCertification` does not return the field.

### The lookup code in the station's printer queue and the fruit batch's labels (#326)

Additive: a new optional query parameter `label_code` of `claimStationSignIn`
(`POST /v1/gateways/{id}/station-delegations/claim`), `syncStation` (`POST /v1/gateways/{id}/station-sync`) and
`allocateFruitBatch` (`POST /v1/sessions/{id}/fruits/batch`), and a new field of `StationLabel` and of `FruitLabel`
returned only with `label_code=1`, all marked `x-not-in-sdk: true` (the two station operations are not part of the
partner SDK clients either; the fruit batch's description and 400 answer keep their earlier text for the clients,
`x-sdk-description` and `x-sdk-object`), so the generated code is unchanged. Without the parameter every answer is
exactly as before, and the single allocation (`POST /v1/sessions/{id}/fruits`) never carries the field. StationLabel
and FruitLabel are closed (`additionalProperties: false`), so a new field there would break a client that refuses
unknown fields; it is accepted because the server returns it only with `label_code=1`, which no client written
against the earlier document sends. Any value of `label_code` other than `0` or `1` is refused (400
`bad label_code`; the fruit batch's refusal has its `fruit.batch_allocate.failed` audit row, as every refused batch).

- `labels[].label_code`: the fruit's lookup code (#288) in its grouped form (`7YD1R-1YMWA-W5MVB`), derived from the
  fruit's public id. The edge station's 40 x 30 mm fruit label prints it beside the QR code, as the console's label
  does, so a person whose QR code cannot be scanned can type it on the scan page; `GET /v1/public/resolve` answers it
  with the fruit. A GTIN lot's QR URL is a GS1 Digital Link, which does not carry the public id, hence the field. The
  Python SDK's edge station asks for it from its next release (the Python SDK's changelog).
- `items[].label.label_code` (the fruit batch with `label_code=1`): the same code in each fruit's label payload, for
  a partner that prints the labels of a block of fruits ahead of the line; the Python SDK's ZPL driver
  (`fruit_label`) prints it from its next release.

### A public lot whose signature check is still in progress says so (#329)

Additive: a new optional query parameter on an anonymous operation, and a new member that only a caller sending it
receives (both `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged and never receives the member);
and a cache change.

- `getPublicLot` (`GET /v1/public/lots/{publicId}`) takes `signatures_complete`: `1` adds
  `verification.signatures_complete`, true when the answer re-verified every accepted event of the lot (so
  `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 (at most 128 envelopes per request; the count then covers the
  events checked so far); `0` or none leaves it out, as before; any other value is 400 `bad signatures_complete`,
  refused before the record is looked up and never cached.
- An answer whose re-verification is not complete is now `Cache-Control: private, no-store` (with or without the
  parameter) instead of the public edge caching, so a shared cache never keeps and serves a count that is still growing
  (the same lot showed 128, 256, 384 and 512 on successive loads). A complete answer is cached as before.

### The console work home: choose samples and logger readings missing (#283)

Changes a session-only, console-only answer (`getConsoleHome`, `x-session-only` and `x-not-in-sdk`): no partner client
receives it, and the console's own client is generated with this document. The closed objects gain a member each; no
partner client can meet the new members (owner decision O3).

- `sections.work.tasks.sample`: closed or packed lots never sampled, since their close.
- `sections.shipments.logger_missing`: `{count, oldest}`, the shipments departed in the last 30 days whose temperature
  logger check is `missing` or `incomplete`, the 5 that departed first.

### A lab's logins: invite a lab analyst, list and revoke (#283)

Additive: three new operations of the platform admin console (all `x-not-in-sdk`, so the partner SDK clients' generated
code is unchanged).

- `createLabInvitation` (`POST /v1/labs/{code}/invitations`): a one-time link (72 hours) for a lab analyst of an active
  lab, answered once like `createAdminInvitation`. The login belongs to the company record kept only for lab logins
  (`croppath-labs`, created with the first invitation; owner decision O1), never to a customer company: an email whose
  account holds another membership is 409 `lab_account_must_be_separate`; one that already signs in for the lab is 409
  `already_a_member`; one turned off by CropPath support is 409 `lab_login_turned_off`; a suspended lab is 409
  `lab_suspended`. At most 50 pending links and 30 new links an hour for each lab, counted on its own (409
  `too_many_pending_links`, `too_many_links`): one lab at its cap never blocks another. Platform admins only, through a
  session with a recent password. Audited `account_link.create`.
- `listLabLogins` (`GET /v1/labs/{code}/logins`): who signs in for the lab and its pending invitations, never a link.
- `revokeLabInvitation` (`POST /v1/labs/{code}/invitations/{id}/revoke`): audited `account_link.revoke`; another lab's
  invitation, or a link that is no lab invitation, is a 404.
- `inspectAccountLink` answers `role: lab` for a lab analyst's invitation: `AccountLinkInfo.role` gains the value (a
  new response enum value; the console, generated with this document, refused the answer without it, so the invitee
  could not join). The partner SDK clients keep the 0.2.0 list (`x-sdk-enum`); no partner client inspects a lab
  invitation.
- Company invitations (`createInvitation`, `createAdminInvitation`) for an email whose account is such a lab login are
  refused 409 `lab_account_must_be_separate`, and the lab logins' company takes no company invitation (409
  `lab_logins_only`).
- `startCompanyOffboarding` refuses the lab logins' company record (409 `lab_logins_company`): its departure would
  refuse every lab invitation and end every lab login. `listTenants` with `platform=1` marks it `platform: true`, like
  the company of CropPath's platform admins, so the console does not offer the action.

### A suggested code for a new lot (#315)

Additive: a new operation (`x-not-in-sdk`, so the partner SDK clients' generated code is unchanged).

- `suggestLotCode` (`GET /v1/lots/suggested-code`): the code the console's create-lot form pre-fills,
  `LO-YYMMDD-NNN` (today in Asia/Ho_Chi_Minh, the company's next number of the day, three digits). The code stays the
  company's choice: `createLot` takes any valid code, and refuses a code taken since the suggestion (409
  `lot_code_already_exists`). A read, not audited; for the callers who may create a lot (the `lot_write` policy).
  It sits before `getLot`, whose path it matches: no lot code is lower case, so no lot was reachable there.

### The company's recalls (#322)

Additive: a new operation marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged), with its schema `RecallList`; no existing operation or schema changes.

- `listRecalls` (`GET /v1/recalls`): the company's lot recalls and withdrawals, newest first (at most 100), each
  `{lot, recall}` with the same recall view as `getLotTrace` (`LotRecall`, its outbound notice included), and the
  counts `total` and `notices_pending` (notices stored and not sent yet). Never cached. Same roles as `getLotTrace`:
  tenant and platform admins and auditors; operators and labs are refused. Not audited (a read).

### Spray records in the lot history (#322)

Additive for every published client: `listLotApplications` is not part of the partner SDK clients (`x-not-in-sdk`), and
its answer `LotApplications` gains the required member `sprays` (the console, its only client, is released with
this document).

- `listLotApplications` (`GET /v1/lots/{lot}/applications`): `sprays` lists 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 listed period to the
  lot's harvest day, both included, oldest first (at most 200, the newest kept), each `{id, sprayed_on, product,
  active_ingredient, withholding_days, safe_from, withholding_status}` with its withholding status at the harvest day.
  A lot's inputs and its growing area's spray log now agree. The records are listed only: whether a spray record holds
  a harvest is still the open owner question of #241.

### A fruit taken out at grading answers its own 404 (D27, #322)

Additive for a client that reads the error's `code`: `getPublicFruit` (`GET /v1/public/fruits/{publicId}`) answers a
fruit taken out at grading (status rejected) of a public lot with 404 `fruit_rejected` instead of `not_found`, with
the same headers, so the page its label opens can say the fruit was rejected at grading. The body names nothing about
the fruit or its lot, no scan is logged, and every other route of the fruit answers the uniform `not_found`. The status
is still 404 under the public 404 time floor (#110). The partner SDK clients keep the operation's released 404 object
(`x-sdk-object`), so their generated code is unchanged.

### The lab drawn for a lot's sampling is approved for its market (D15, #322)

Additive for a client that reads the error's `code`: `sampleLot` (`POST /v1/lots/{lot}/samples`) answers 409
`no_approved_lab_available` for a market whose official approved-lab list the deployment imports
(`AGRITRACE_LAB_LIST_MARKETS`) when no lab in force with an active key has current approvals for that market covering
every analyte of the rule; such a market's lab is drawn only among the labs that do. For any other market the lab is
drawn among every lab in force with an active key, as before, and the fallback is logged as a warning. The `lot.sample`
audit row records the draw (`lab_draw`: `approved_list` or `any_lab`). The partner SDK clients keep the operation's
released description (`x-sdk-description`) and 409 object (`x-sdk-object`), so their generated code is unchanged.

### The export carton label's lookup code (#288)

Additive: a new optional query parameter of `getLotExportLabel` (`GET /v1/lots/{lot}/export-label`), `label_code`, and
a new `ExportLabelCarton` field returned only with `label_code=1`, both marked `x-not-in-sdk: true` (not part of the
partner SDK clients, whose generated code is unchanged). Without the parameter the label reads exactly as before.
ExportLabelCarton is closed (`additionalProperties: false`), so a new field there would break a client that refuses
unknown fields; it is accepted because the server returns it only with `label_code=1`, which no client written against
the earlier document sends. Any value of `label_code` other than `0` or `1` is refused (400 `bad label_code`).

- `cartons[].label_code`: the carton's lookup code in its grouped form (`7YD1R-1YMWA-W5MVB`, three groups of five
  Crockford base 32 characters), derived from the carton's public id. The console prints it under the carton's QR code
  so a person whose QR code cannot be scanned can type it on the scan page; `GET /v1/public/resolve` answers it with
  the carton's lot, under the same rules as every other form. A carton of a GTIN lot has a GS1 Digital Link as its QR
  URL, which does not carry the public id, hence the field.

### Coded addresses required before a lot is packed and before an export label (#273)

Breaking for a client that packs lots: the pack event now needs coded addresses (owner decision D5). Viet Nam has had
no district level since 1 July 2025, so a lot is packed only once the addresses its seal records are picked from the
official list of administrative units, a province and a commune.

- `sealLot`: the first seal of a lot (the pack event) is refused with 409 `address_not_coded` while the lot's packing
  house, its growing area, or the company profile in Viet Nam is not coded yet. The answer's new member `details`
  lists each record to fix, `{kind, code}`: `facility` or `growing_area` with its code, or `company_profile` with a
  null code. Nothing is written apart from the refusal's audit row (`lot.seal.failed`). A company profile abroad, or a
  company without a profile, needs nothing. A later seal change of a packed lot is not checked. `details` is optional
  in the shared `Error` schema, given by this refusal only, and marked `x-not-in-sdk: true`: the partner SDK clients
  read an error's `code` and `error` alone, and their generated code is unchanged.
- `getLotExportLabel`: the problem `address_not_coded` (the company profile's address in Viet Nam is not coded yet)
  is now raised, so such a label is not ready and its print is refused (409 `label_not_ready`).
### The commune map of a public record's growing area (#293)

Additive: a new anonymous operation, a new optional query parameter on two anonymous operations, and a new member that
only a caller sending it receives (all `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged and never
receives the member).

- `getPublicLot` (`GET /v1/public/lots/{publicId}`) and `getPublicFruit` (`GET /v1/public/fruits/{publicId}`) take
  `map`: `1` adds `growing_area.map` (lot) or `origin.map` (fruit) to the record; `0` or none leaves it out, as before;
  any other value is 400 `bad map`, refused before the record is looked up and never cached.
- `PublicCommuneMap` (`map`): `{url, osm_relation}`, or null. The map shows the commune the record already names in
  words, never the orchard: its OpenStreetMap boundary on map tiles CropPath renders itself. It is present when exactly
  one commune of the OpenStreetMap commune dataset in force matches the growing 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. `url` is the image's same-origin path; it names the two datasets and the commune's OpenStreetMap
  relation only, never the growing area, its code or a GLN. `osm_relation` is that relation's id
  (https://www.openstreetmap.org/relation/{osm_relation}).
- `getPublicCommuneMap` (`GET /v1/public/maps/{tileset}/{communes}/{osm_id}.svg`): the image, `image/svg+xml`, 448 x
  252 pixels, at most 400 KiB. Its map tiles are embedded as `data:` PNG images, so loading it requests nothing from
  another site; it holds no script and no external reference, and carries the attribution "© OpenMapTiles ©
  OpenStreetMap contributors". Its bytes never change for a given path: `Cache-Control: public, max-age=31536000,
  immutable`, an `ETag` (304 on a matching `If-None-Match`), `X-Content-Type-Options: nosniff` and its own
  `Content-Security-Policy`. A path that names nothing imported is 404 `not found: maps`.

A page that shows the image must also show the attribution near it, with "OpenMapTiles" linked to
https://openmaptiles.org/ and "OpenStreetMap contributors" linked to https://www.openstreetmap.org/copyright. The public
lot and fruit pages ask for the map.

### The work homes of the console and the lab portal (#286)

Additive: two new read operations, marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated
code is unchanged) and session-only (an API token, an API client or the legacy token gets 403 `role_not_permitted`),
with their schemas `ConsoleHome` and `LabHome`, one schema per section (`ConsoleHome...`, `LabHome...`) and
`ConsoleHomeTask`; no existing operation or schema changes. Both write nothing, so they are not audited, and answer
`Cache-Control: no-store`; the server serves one answer for `max_age_s` seconds after its `generated_at` (10 seconds
for the console, 30 for the lab). Each section has `state`: `ok` with its figures, or `unavailable` (with `reason`
`query_failed`, `OverviewSectionUnavailable`) when it could not be read, while the other sections answer.

- `getConsoleHome` (`GET /v1/console/home`): the console's work home for the selected company. The measurement sessions
  open or paused now, each with `opened_by_you` (whether the caller opened it; who else did is not sent); 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.full` says when a packing house has more); the open shipments; the device messages
  waiting for review; the devices and stations with whether each device is ready and its calibration's end; and
  today's counts in the Vietnam calendar day. tenant_admin and platform_admin (acting for the company through
  X-Tenant) read the whole company; an operator reads the packing houses of their role (all of the company's when
  their role names none). Auditors and lab users are refused (403). A company that does not exist answers 404.
- `getLabHome` (`GET /v1/lab/home`): the lab portal's home for the caller's lab: its status, accreditation, market
  approvals and keys, and, among its newest 500 samplings, those waiting for results (with how many were drawn more
  than `target_hours`, 48, ago), the reports stored without their PDF original and the reports stored in the last 7
  days. A lab user only (its own lab); a lab that is not in the registry answers 404.

### Customs dossier format 2: commune and province (#273)

Breaking for a client that refuses unknown members: a new document format. Viet Nam has had no district level since 1
July 2025, so a lot packed from now on whose packing house or growing area is coded by official administrative unit
codes has a customs dossier in format `agritrace-customs-dossier/2`. A lot packed from now on whose packing house and
growing area are both not coded keeps `agritrace-customs-dossier/1`, so their district text is kept. A dossier keeps
the format of its sealed facts for good: every lot packed before keeps `agritrace-customs-dossier/1`, byte for byte as
before, with the same seal digest and document digest.

- `getPublicLotCustomsDossier`: `format` may be `agritrace-customs-dossier/2`. Only `sealed` differs: in format 2,
  `sealed.growing_area` is `{code, commune, commune_code, province, province_code}` or null, `sealed.packing_house` is
  `{code, name, commune, commune_code, province, province_code}`, and `sealed.admin_units_version` is the version of
  the official list of administrative units the codes come from (for example `vn-2026-10-17`). The codes are the official 2-digit province and 5-digit commune codes, null for a record that was
  not coded when the lot was packed (its names are then its text). Read the members according to `format`.
- The seal digest is checked the same way in both formats: `seal.value` is the SHA-256 of the RFC 8785 (JCS) form of
  `sealed`. The document digest is unchanged in meaning.
- `getPublicLotCustomsDossierPrint`: a format-2 dossier prints "commune, province". A format-1 dossier of a lot packed
  on or after 1 July 2025 labels its district as the district before that date. The JSON document is not changed.
- `getLotRecordsExportCsv`, `getLotRecordsExportJson`, `getRecordsExportCsv` and `getRecordsExportJson`: the
  `sealed_record` row of a lot packed from now on in format 2 gives the packing house's `location_address` and the growing area's
  `supplier_address` as "commune, province", as sealed; `sealed_record.facts` holds the format-2 members.
- The partner SDK clients' generated code is unchanged (their `PublicCustomsDossier` describes format 1). A strict
  client generated before this change, such as one that refuses unknown fields, refuses a format-2 dossier until it is
  regenerated from the current document.

### Localities of coded addresses read "commune, province" (#273)

No change to any schema: only the text of some string fields. For a facility or growing area coded by official
administrative unit codes (Viet Nam has had no district level since 1 July 2025), the public lot record's
`facility.locality` and `growing_area.locality`, the public fruit record's `harvest_place`, the records export's
`location_address`, `location_description` and `supplier_address`, the recall export's `location_description` and the
FSMA 204 rows' addresses and `traceability_lot_code_source` give the commune and province instead of a district. A
record not coded yet reads exactly as before. Documents already issued and sealed records are never rewritten.

### Export label origin by commune and province, and a coded company address before the next label (#273)

The origin of a growing area coded by official administrative unit codes is printed as its commune and province: Viet
Nam has had no district level since 1 July 2025. A growing area not coded yet keeps its district and province, as
before. The new query parameter, the new origin alternative and the producer's `commune` are marked `x-not-in-sdk:
true` (the partner SDK clients' generated code is unchanged).

- `getLotExportLabel` takes a new optional query parameter, `admin_units`. With `1`, `fields.origin` is
  `{province, commune, district}`: a coded area has its commune and province and `district` null; an area not coded
  yet has its province, district and commune text. `fields.producer` also carries the company's `commune`. `0` or no
  parameter answers as before, except that the origin of a coded area is null, since the closed `{province,
  district}` has no commune: read the label with `admin_units=1` to print it. Any other value is refused (400
  `bad_admin_units`). Breaking for a client that asks for it, and only such a client gets it.
- The origin a label needs: the province and commune of a coded area, or the province and district of an area not
  coded yet (`origin_missing` otherwise). Readiness is the same with and without `admin_units`.
- New problem `address_not_coded` in `problems` (additive: a new enum value a client may receive): the company
  profile's address in Viet Nam is not coded yet, so the label is not ready and its print is refused (409
  `label_not_ready`, naming it) until a company admin picks the province and commune from the official list. A
  profile abroad, or a company without a profile, does not raise it.

### Facilities, growing areas and company profiles take the address by official code (#273)

Additive in the requests; the new response members come only on request. Since 1 July 2025 an address in Viet Nam is a
province and a commune (xã, phường or đặc khu): there is no district level any more. The new request fields, the new
query parameter, the new response members and the new 503 are marked `x-not-in-sdk: true` (not part of the partner
SDK clients, whose generated code is unchanged).

- `createFacility`, `updateFacility`, `proposeFacility`, `createGrowingArea`, `updateGrowingArea` and
  `putCompanyProfile` take two new optional request fields, `province_code` (2 digits) and `commune_code` (5 digits),
  the official codes `getAdminUnits` lists; both or neither. With them `province`, `district` and (growing areas)
  `commune` must be absent or null, and the server writes the official names: `province` and `commune` hold them and
  `district` is null. The commune must lie in that province by the official list, never by its digits.
- New refusals, all for a request that sends the codes (a request without them is refused exactly as before):
  400 `admin_unit_unknown` (a code that is not in the list in force, also one only an older version has),
  `commune_not_in_province`, `district_with_codes`, `invalid_province` or `invalid_commune` (a name sent with the
  codes), `invalid_province_code` or `invalid_commune_code` (a malformed code, or one without the other), and for a
  company profile whose `country` is not VN, `invalid_country` (the codes apply in Viet Nam only; abroad `province`
  and `district` stay the free-text region and locality). 503 `administrative_units_catalog_unavailable` when the
  server has no list in force to check the codes; nothing is written.
- `listFacilities`, `getFacility`, `listGrowingAreas`, `getGrowingArea`, `getCompanyProfile` and
  `getCompanyPublicIdentity` take a new optional query parameter, `admin_units`: `1` adds `province_code`,
  `commune_code`, `admin_units_version` (the version of the list the codes come from, for example `vn-2026-10-17`; a
  code is only meaningful with its version), `address_status` (`coded`, `choose_commune`, `needs_commune`,
  `outside_vietnam`, or null for a record not reviewed yet), `address_before_reform` (the province, district and
  commune text the record held before it was coded, kept for good) and `address_candidates` (the commune codes to
  pick from, for `choose_commune`), and for facilities and company profiles `commune`. On the public identity it adds
  `public_producer.commune`, hidden for a household business like its district unless it opted in to its full address.
  `0` or no parameter answers exactly as before; any other value is refused (400 `bad_admin_units`). Since the
  members appear in objects the document closes, they are breaking for a client that asks for them, and only such a
  client gets them: a client generated before this change cannot send the parameter, so it never receives them. A
  write's answer never carries them.

### Text-only addresses of facilities, growing areas and company profiles deprecated (#273)

Deprecation of a request shape, not of a route: an address in Viet Nam given as free text only. The `province` and
`district` text fields (and, on growing areas, `commune`) of `createFacility`, `updateFacility`, `proposeFacility`,
`createGrowingArea` and `updateGrowingArea` are marked `deprecated: true`. `province` and `district` of
`putCompanyProfile` are deprecated for a profile in Viet Nam only (`country` VN or absent), so their descriptions say
so and they are not flagged: in another country they stay the free-text region and locality.
Replacement: `province_code` and `commune_code` (entry above).

- Until the sunset a text-only address is still accepted: the record keeps the text, is stored as not yet coded
  (`address_status` `needs_commune`, with the text in `address_before_reform`) and waits for a company admin to pick
  its commune from the official list.
- A successful update that sends the record's own stored text back unchanged (compared after Unicode NFC
  normalisation and trimming; a client that reads the record and writes it all back) changes no address: the record
  keeps its codes, status and candidates, and the answer carries no deprecation header.
- Every other answer to such a request, errors included, carries the deprecation headers; any other request (with the
  codes, without any address text, a profile abroad, every read) carries none:
  - `Deprecation: @1792195200` (RFC 9745): deprecated at the start of 17 October 2026, UTC;
  - `Sunset: Sat, 01 May 2027 00:00:00 GMT` (RFC 8594);
  - a `Link` header naming this entry with `rel="deprecation"` and `rel="sunset"`.
- Sunset: 1 May 2027. From then a text-only address in Viet Nam may be refused; that refusal will be its own change,
  recorded here as the removal.

### Viet Nam's provinces and communes by official code (#273)

Additive: one new operation marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged), with its schemas `AdminUnitProvinces`, `AdminUnitCommunes`, `AdminUnitProvince`, `AdminUnitCommune` and
`AdminUnitSource`.

- `getAdminUnits` (`GET /v1/admin-units`, anonymous): the official list of Viet Nam's administrative units, two levels
  since 1 July 2025, as the National Statistics Office publishes it. Without `province` it answers the provinces (2-digit
  codes); with `province=<code>` that province's communes (xã, phường, đặc khu; 5-digit codes). Each unit has its
  `code`, official Vietnamese `name` and `kind`. The list is versioned (`version`, for example `vn-2026-10-17`, and
  `valid_from`): by default the version in force on Viet Nam's date, or an older one named by `version=`. A code is
  only meaningful with its version, since codes were reused across the 2025 reform.
- The first version is the official list as of 17 October 2026 (`vn-2026-10-17`, in force from 20 September 2026):
  34 provinces and 3,321 communes (2,599 xã, 709 phường, 13 đặc khu). Every answer credits its source in `source`: the
  National Statistics Office of Viet Nam (Cục Thống kê, Ministry of Finance), https://danhmuchanhchinh.nso.gov.vn/.
- Cacheable: `Cache-Control: public, max-age=3600` and a strong `ETag`; a matching `If-None-Match` answers 304.
- An unknown province or version answers 404 `not_found` with the same body and headers whatever was asked; a malformed
  one 400 (`bad_province`, `bad_version`); no catalog in force on the server 503
  (`administrative_units_catalog_unavailable`). Rate limited per client by the same bucket as `/v1/public/*`.

### Names in the console's top bar; the platform company (#282)

Additive for every partner client: two new members of a session-only answer, and a new optional query parameter whose
member only a caller sending it receives (all `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged).

- `getCurrentSession` (`GET /v1/auth/me`, cookie only): `tenant_name`, the name of the company the request acts for,
  and `lab_name`, the name of a lab user's lab; each null when there is none. No API token or API client can call this
  operation, so no partner client receives them.
- `listTenants` (`GET /v1/tenants`) takes `platform`: `1` adds `platform` to each company, true for the company of
  CropPath's platform admins, which `startCompanyOffboarding` always refuses (409 `platform company`); `0` or none
  leaves it out, as before; any other value is 400 `bad platform`.

### Hand-declared harvests in a growing area's volume; corrections made while measuring (#281)

Meaning changes, no schema change (the partner SDK clients' generated code is unchanged).

- `getGrowingAreaVolume` (`GET /v1/growing-areas/{code}/volume`), `getVolume` (`GET /v1/volumes/{growing_area}/{season}`)
  and the lot summary's `volume`: `declared_kg` now also counts the harvests a company declared by hand for the area
  and season (`declareHarvest`, `POST /v1/growing-areas/{code}/harvests`), as the packing view's mass balance already
  counted them in `harvested_kg`; `headroom_kg`, where given, drops by the same amount. Before, an area whose only harvest was
  declared by hand read 0 kg declared. The check made when a device's harvest or receive event arrives is unchanged.
- `getPublicLotCorrections` and `getPublicFruitCorrections`: 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 no longer counted in `after_public`, only in `count`. A `measurement` correction made at any other
  time after `public_since` (after the session closed, while it was paused, or while only another session of the lot
  was running), and every other step's correction after `public_since`, are counted as before.

### What holds a public lot or fruit at its trust tier (#280)

Additive: a new optional query parameter on two anonymous operations, and a new member that only a caller sending it
receives (both `x-not-in-sdk`, so the partner SDK clients' generated code is unchanged and never receives the member).

- `getPublicLot` (`GET /v1/public/lots/{publicId}`) and `getPublicFruit` (`GET /v1/public/fruits/{publicId}`) take
  `trust_limits`: `1` adds `trust.limited_by` to the record; `0` or none leaves it out, as before; any other value is
  400 `bad trust_limits`, refused before the record is looked up and never cached.
- `PublicLot.trust.limited_by`: what holds the lot at `tier` before an open hold or a recall caps it. `["sealed"]`: 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 (each journey step may then show a higher tier than the lot). Otherwise each journey step that
  decides the tier, in journey order (`registration`, `harvest`, `measurement`, `lab`, `packing`, `shipping`): 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` takes the `measurement` step's place
  when every measurement record of the lot had its ripeness reading overridden by a sensory assessment: an overridden
  record is Self-declared whatever its device signature.
- `PublicFruit.trust.limited_by`: the same for a fruit. When the lot's tier decides the fruit's, what holds the lot
  (its `registration` step included, which the fruit record's journey does not show); `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, so it stays Self-declared whatever its device signature, its lot or its seal.

The public lot and fruit pages ask for it, and a Self-declared record outside a hold or a recall states in one
sentence why it is Self-declared.

### Export labels: codes cross-checked against the published code lists (#280)

Not breaking; no operation, parameter or schema changes. A China export label (carton or pallet) now counts the
growing area's and the packing house's registration codes as cross-checked when each is matched, active, on a
published code list a platform admin imported that is not older than the configured age, the same check as the lot's
registration step. Until now no code was ever cross-checked, so with the built-in China template a label was never
ready, no carton label could be printed, and the departure's carton label check lowered every shipped lot's packing
step to Self-declared. Without an imported list, or with a stale one, nothing changes: the label stays not ready with
`orchard_code_not_cross_checked` and `packing_house_code_not_cross_checked`.

### The admin home's overviews (#274)

Additive: two new read operations of the console's admin home, marked `x-not-in-sdk: true` (not part of the partner
SDK clients, whose generated code is unchanged) and session-only (an API token, a platform_admin one included, or an
API client gets 403 `role_not_permitted`), with their schemas `CompanyOverview`, `PlatformOverview`,
`OverviewSectionUnavailable`, one schema per section (`CompanyOverview...`, `PlatformOverview...`) and
`PlatformOverviewCompany`; no existing operation or schema changes. Both write nothing, so they are not audited, and
answer `Cache-Control: no-store`; the server computes an answer at most every 30 seconds and serves it for `max_age_s`
seconds after its `generated_at`. Each section has `state`: `ok` with its figures, or `unavailable` (with `reason`
`query_failed`) when it could not be read, while the other sections answer.

- `getCompanyOverview` (`GET /v1/company/overview`): the selected company's counts (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). Counts and the company's own
  codes only; another company's records never count. tenant_admin, auditor and platform_admin (acting for the company
  through X-Tenant); an auditor's answer (`view` auditor) leaves out `approvals`, `team`, `integrations`, `email` and
  `requests.personal_data_open`. A company that does not exist answers 404.
- `getPlatformOverview` (`GET /v1/platform/overview`): for platform_admin only, the service's health (as
  `getAdminHealth`), the traffic and ingest of the server that answers since it started (`process.started_at`) with
  per-minute figures measured while the overview is opened, the queues, the work waiting on CropPath, sign-in security
  and the companies (at most 50, names, codes and counts only).

### Live streams: credential checks and the session's idle time (#129)

Not breaking; no operation, parameter or schema changes. For `streamSession` (`GET /v1/sessions/{id}/stream`) and
`streamEnvelopes` (`GET /v1/envelopes/stream`):

- The credential and the grant of an open stream are checked again every 60 seconds (configurable by the operator),
  not on every read of the stream. On a server that runs PostgreSQL, a logout, a revoked session or API credential, a
  disabled user, a password change or a changed grant ends the stream at once, or within about a second while the
  server is reconnecting to its database; only when the server's database connection silently stops delivering its
  notifications can the stream end up to about 35 seconds late. On a server that runs
  SQLite it ends the stream at the next check, so a revoked caller can receive events for up to that interval; a
  credential that expires ends the stream at the next check too.
- An open stream no longer keeps a signed-in session alive: the session expires after 12 hours without another
  request, and its stream then ends at the next check, without an `end` event (the reconnect is refused). Other
  requests of the session refresh its idle time as before. API tokens have no idle time and are not affected.
- Events, heartbeats, `retry`, `Last-Event-ID` resumption, the lifetime and the stream caps are unchanged.

### A growing area's boundary from a land-use right certificate (#250)

Additive: four new operations marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged), with their schemas `LandCertificateCreate`, `LandCertificateCheck`, `LandCertificateCheckResult`,
`LandCertificate`, `LandCertificateSummary`, `LandCertificatePage` and `LandCertificateWalkComparison`; no existing
operation or schema changes.

- `checkLandCertificate` (`POST /v1/growing-areas/{code}/land-certificates/check`): the same corners and central
  meridian without the photo's hash, answered with the outline the certificate would propose or with the refusal it
  would meet before its photo matters (the corners, the outline, the area). It stores nothing, so it is not audited.
  The console calls it before it uploads the certificate's photo, so a refused certificate does not leave the photo
  behind as an ordinary company upload.

- `submitLandCertificate` (`POST /v1/growing-areas/{code}/land-certificates`): the parcel corners printed on a land-use
  right certificate's parcel map (VN-2000 plane coordinates, X northing and Y easting in metres, of the province's
  central meridian `central_meridian_min`) with the hash of an uploaded photo of the certificate page. The server
  converts the corners to WGS 84 with the transformation parameters of Decision 05/2007/QD-BTNMT in the formulas of
  Circular 973/2001/TT-TCDC; the outline becomes the area's pending boundary proposal, decided in the boundary proposal
  queue like any other. Audited (`growing_area.land_certificate.submit`, never the corners or the photo).
- `listLandCertificates` (`GET /v1/growing-areas/{code}/land-certificates[?polygon_sha256=]`) and
  `getLandCertificate` (`GET /v1/growing-areas/{code}/land-certificates/{id}`): the certificates kept as the evidence
  of a proposal or a boundary version with the same `polygon_sha256`, compared with the registered size and with the
  area's latest boundary walk; the corners only in the single certificate.

Only the area company's tenant admins and a platform admin acting for it, never an OAuth client; another company's
area answers 404. The photo and the corners are never public. `getAttachment` (`GET /v1/attachments/{sha256}`, and
its `/peaks`) answers 404 for the photo once a certificate names it, unless the caller may read land certificates
through a signed-in session: an auditor, an API token or an OAuth client with `attachment_read` no longer reads it
(the partner SDK clients keep the operation's released description, `x-sdk-description`).

### Which location check applies to a growing area (#247)

Additive: a new read operation marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged), with its schemas `LocationCheck`, `CommuneVerdictCounts` and `PositionCommune`; no existing operation or
schema changes. It writes nothing, so it is not audited.

- `getAreaLocationCheck` (`GET /v1/growing-areas/{code}/location-check?from=&to=`): which check ingest makes now for
  the caller's company's positions of the area (`applies`: `plot_boundary`, `commune` or `none`), the commune
  boundary dataset in force, whether the registered commune is a commune of it (`name`: `matched`, `unmatched`, e.g. a
  name from before the 2025-07-01 reform, or `missing`), the commune verdict counts over at most 31 days of reception
  times, and the communes the area's judged positions fell in (`position_communes`, the area by point: only for a
  platform admin and the operators and tenant admins of the area's owning company, null for the others). The commune
  names come from OpenStreetMap: `attribution` and `copyright` come with every answer that names a dataset. Same
  roles as `getVerdictMap`; another company's area answers 404. Never public.

### Reserved device and gateway ids (#126)

One **BEHAVIOUR CHANGE**; the partner SDK clients' generated code is unchanged (the changed descriptions keep their
released text for the clients through `x-sdk-description`).

- **BEHAVIOUR CHANGE**: `createDevice` (`POST /v1/devices`) and `createGateway` (`POST /v1/gateways`) answer 400
  (`invalid device_id` / `invalid gateway_id`) for an id that starts with `agritrace-`, in any letter case. Those
  names are the platform's own broker identities (the backend and the ingest workers), whose certificates the
  self-hosted broker grants by name before it asks the registry.

### Per-company quotas (#134)

One **BEHAVIOUR CHANGE** and a new field of a session-only answer; the partner SDK clients' generated code is
unchanged (the new field and its schema are marked `x-not-in-sdk`, and the changed descriptions keep their released
text for the clients through `x-sdk-description`).

- **BEHAVIOUR CHANGE**: 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: calls per minute (default 1,200) and calls per UTC day (default 500,000),
  set by the platform operator (`AGRITRACE_TENANT_QUOTAS`, per company or for all). 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, changed or audited. A call refused by
  the daily quota is not counted. Console requests are not held to these quotas.
- **BEHAVIOUR CHANGE**: `ingestEnvelope` (`POST /v1/ingest/{route}`) answers 429 `too_many_requests` with
  `Retry-After` and an `Error` body when the company of the sending device's or gateway's certificate is over its
  ingest quota (default 100 messages a second with bursts of 3,000), whatever company the route names; nothing is read
  or stored, and the device sends the message again later (the SDK transports already retry a 429). 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. Over MQTT nothing is refused: a company
  over its quota has its messages stored at its quota's rate while other companies' messages go straight in.
- `getCompanyUsage` (`GET /v1/company/usage`, session-only) answers `quotas` (`CompanyUsageQuotas`): the company's
  API calls per minute and per day with today's calls (`api_day_warning` from `warn_percent`, `api_day_reached`), and
  its ingest rate and burst with the device messages waiting in its ingest backlog, and `stored`
  (`CompanyUsageStored`): the company's envelopes, the public scans of its fruits, its stored files and their bytes.
  `CompanyUsage` is a closed object, so the breaking-change check lists these new fields; they are accepted because
  the operation refuses every bearer credential (403), so no partner client ever receives them.
- `getMetrics` (`GET /v1/metrics`) adds the companies' quotas and their use (`agritrace_tenant_quota`,
  `agritrace_tenant_api_calls_today`, `agritrace_tenant_api_refused_total`, `agritrace_tenant_ingest_backlog`,
  `agritrace_tenant_ingest_deferred_total`, `agritrace_tenant_ingest_drained_total`,
  `agritrace_tenant_ingest_backlog_full_total`, `agritrace_tenant_ingest_refused_total`,
  `agritrace_tenant_ingest_backlog_bytes`), labelled by company id, and `agritrace_ingest_unidentified_refused_total`
  (no label).

### Email: a person's email setting and an email's unsubscribe link (#270)

Additive: three new operations marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged), with their schemas `EmailSettings`, `EmailSettingsUpdate`, `EmailUnsubscribe` and
`EmailUnsubscribed`. When the server sends email (the operator has configured an SMTP provider), a one-time link
created by `createInvitation`, `createMemberPasswordLink`, `createAdminInvitation` or `createAdminRecoveryLink` is also
emailed to its person; the response is still the only place the link is shown.

- `AccountLinkCreated`, the 201 response of those four operations, gains `emailed` (boolean, `x-not-in-sdk`): whether
  this link's email was queued. It is false when the server sends no email or cannot email that address, and the link
  must then be passed on by hand. A new field of a closed object, accepted as breaking by the check because all four
  operations are session only: they refuse every bearer credential, so no SDK client receives this response.

- `getMyEmailSettings` (`GET /v1/auth/email-settings`, session only): whether the signed-in person gets the
  notification, alert and recall emails, their emails' language, and `delivery`: whether this server sends email at
  all.
- `updateMyEmailSettings` (`PUT /v1/auth/email-settings`, session only): turn those emails on or off and set the
  language; audited (`auth.email_settings.update`).
- `unsubscribeEmail` (`POST /v1/public/email/unsubscribe`, anonymous): the unsubscribe link of a notification, alert or
  recall email posts its signed token here; 200 turns that person's emails off (one `email.unsubscribe` audit row when
  it changed), 400 `invalid_link` for a token that is not valid. Rate limited by the public and the login buckets.

### EPCIS capture takes sensor data (`sensor_reporting`) as Self-declared (#238)

Additive: `captureEpcis` (`POST /v1/epcis/capture`) accepts events whose `bizStep` is `sensor_reporting`, which it
refused before (`unsupported_biz_step`). New response enum values, which the partner SDK clients do not carry
(`x-sdk-enum`; their generated code is unchanged): `observe` in the report's `step`, and `sensor_reporting` (`biz_step`)
with `observe` (`step`) in `listLotCapturedEvents` (`GET /v1/lots/{lot}/captured-events`).

- A `sensor_reporting` event must be an `ObjectEvent` with `action` `OBSERVE` and a `sensorElementList` (otherwise
  `unsupported_biz_step`), with at most 20 sensor elements and 200 sensor reports (otherwise `event_too_large`). Its
  sensor elements are checked member by member against the GS1 EPCIS 2.0 JSON schema (`invalid_event` naming the
  member). Like every captured event it must name a lot, carton or shipment of the company (`no_reference`,
  `unknown_reference` otherwise) and is stored with `tier` `self_declared`; it never becomes a sensor reading or
  evidence for a trust tier. The other business steps keep their checks exactly as before.

### EPCIS export version 3: GS1 measurement types, units and positions (#238)

Additive: a new value, `3`, of the optional `version` query parameter of `getLotEpcis` (`GET /v1/lots/{lot}/epcis`),
which stays marked `x-not-in-sdk: true` (the partner SDK clients' generated code is unchanged). Version 1 (the default)
and version 2 are exactly as before; any value other than `1`, `2` or `3` is refused (400 `bad version`).

- `version=3` appends the same daily sensor summary events as version 2, with each report in CropPath's export mapping
  of its capability: `type` a GS1 CBV measurement type, written as the bare term the GS1 EPCIS 2.0 JSON schema lists
  (`VolumeFraction` for soil moisture, `Temperature`, `RelativeHumidity` and others), or a CropPath type URI
  (`https://agritrace.vn/voc/<name>`, for example `SoilPH`); `uom` the UN/ECE Recommendation 20 code, or, for a
  capability without one (`light.ppfd`), no `uom` and the UCUM unit as `agri:ucum`. Several capabilities share a GS1
  type, so each report names its capability (`agri:capability`) and what was measured (`agri:feature`: air, soil,
  water, leaf, plant, fruit, device, location or product).
- The device's own GNSS fixes of the day are two reports of type `Angle` with `component` `latitude` and `longitude`,
  `coordinateReferenceSystem` `http://www.opengis.net/def/crs/OGC/1.3/CRS84` and `uom` `DD` (degree), giving the
  day's `minValue`, `maxValue` and `meanValue` over the fixes flagged pass or not evaluated only, as every other report
  counts its values (a failed, suspect or missing fix is never part of the device's position; none of the three when no
  fix counted; no mean longitude when the counted fixes span more than 180 degrees of longitude), with
  `agri:readingCount` (every position reading), `agri:valueCount` (the fixes the statistics took) and `agri:qcFlag`
  (the least trusted flag among every position reading). A fixed device's surveyed install point is not a fix. A device
  that reported positions only now has an event in this version.
- The sensor metadata names the mapping `agri:method/daily-summary-v3`, and a day's event has another `eventID` than in
  version 2. The audit row of the export records `version: 3`. Coordinates appear only in this staff document: the
  public EPCIS document of a sealed lot is unchanged and carries no summary event and no position.

### Operators at an edge station with the WAN down (#85)

Additive: six new operations marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged), with their schemas (`StationSignInRequest`, `StationSignIn`, `StationDelegation`, `StationDelegationList`,
`StationSignature`, `StationClaimRequest`, `StationClaim`, `StationLabel`, `StationSyncRequest`, `StationSync`,
`StationActionRecord`, `StationActionResult`), a new trust reason code and a new case of an existing binding alert; no
existing operation or schema changes.

- `createStationSignIn` (`POST /v1/gateways/{id}/station-delegations`), `listStationSignIns` (`GET` on the same path)
  and `revokeStationSignIn` (`POST /v1/station-delegations/{id}/revoke`): a person signed in to the console lets the
  gateway's edge station record offline fruit actions for them for at most 8 hours, with a one-time code (8 characters,
  10 minutes) typed on the station's screen; lists their pending and active sign-ins (a company admin: everyone's) and
  revokes one. A signed-in session only (an API token, an API client or the legacy token is refused 403); company
  admins, and operators within their facilities. Audited: `station.delegation.issue` (never the code) and
  `station.delegation.revoke`.
- `claimStationSignIn` (`POST /v1/gateways/{id}/station-delegations/claim`), `syncStation`
  (`POST /v1/gateways/{id}/station-sync`) and `replayStationAction` (`POST /v1/gateways/{id}/station-actions`): the
  edge station's own requests, signed with one of the gateway's keys like an envelope. The claim answers the sign-in
  and the label data of the open lots at the station's facility (audited: `station.delegation.claim`, actor the
  operator); the sync answers the state of the station's sign-ins. A replayed action (`accept`, `remeasure`, `print`)
  is applied once, in the station's order, as that operator's action with every existing check; the same record again
  answers what it answered first and writes nothing. Each recorded action writes one `station.action` audit row (actor
  the operator, naming the station). Refusals: 403 for an expired, revoked or unclaimed sign-in, or an operator who may
  no longer act; 404 for another station's or another company's sign-in or fruit; 409 `round_conflict` when an offline
  re-measure's round is not the fruit's next round (recorded once), `out_of_order`, `id_conflict`; 503
  `not_stored_yet` (with `Retry-After`) while an envelope the action follows has not been stored or rejected.
- `fruit_station_offline` is a new trust reason code: a fruit an operator accepted or re-measured offline at a station
  is at most Device-recorded (its own record; it only lowers).
- `superseded_round` (the binding alert) is also raised for a knock stamped with a round a station numbered for an
  offline re-measure that was refused as `round_conflict`, sent through that station: such a knock never binds.

### Verified certifications; public lots of every registry crop (#156)

Additive: no request or response shape changes, and the partner SDK clients' generated code is unchanged (the changed
objects carry `x-sdk-object`, `x-sdk-description`, `x-sdk-example` and `x-sdk-enum`, the new members `x-not-in-sdk`).
One rule changes what an unchanged request returns: **a lot's trust tier now counts only verified certifications**
(below). A lot whose only certification in force on its harvest date is not verified, including one recorded before
this change, loses the harvest step's certification check, so it can show a lower tier than before in
`GET /v1/lots/{lot}/trust`, in the public lot and fruit records and in the `lot.trust_tier_changed` webhook. After the
upgrade the server recomputes once every lot whose growing area has a certification, so the stored tier and the
public pages agree; a lot whose tier drops sends `lot.trust_tier_changed`. A public fruit record shows only a verified
certification in its origin.

- `POST /v1/growing-areas/{code}/certifications` (`createCertification`, `CertificationCreate`): a request is accepted
  as before (`issuer` and `evidence_sha256` stay optional and `scheme` stays free text). A certification is now
  **verified** when its `scheme` is one of VietGAP, GLOBALG.A.P., Organic JAS, Organic EU, Organic USDA, ISO 22000,
  FSSC 22000, BRCGS, IFS and HACCP (the text is compared exactly), it names its certifier (`issuer`) and the SHA-256 of
  the certificate document (`evidence_sha256`, e.g. a PDF uploaded with PUT /v1/attachments/{sha256}), and a
  GLOBALG.A.P. certification's `number` is the producer's GGN (13 digits whose last is the GS1 mod-10 check digit,
  without the `GGN` prefix). Any other certification, including one recorded before, is stored and listed as sent but
  is unverified: it never counts towards a lot's trust tier (the harvest step's certification check counts verified
  certifications only, so a lot whose only certification in force is unverified can show a lower tier than before).
  Send the verified shape to have a certification count, also for one already recorded unverified: the same `scheme`
  and `number` sent again in the verified shape verifies the stored certification in place (201 with the same `id`;
  its `issuer`, validity and `evidence_sha256` become the request's and its `created_at` the time of the change), is
  audited like an addition, and the area's lots are recomputed. The same `scheme` and `number` sent again otherwise
  (the stored one verified, or the request not verified) is still 409 `certification_already_recorded`. The public
  pages show the scheme and the validity only, as before, and only of a verified certification.
- `GET /v1/public/lots/{publicId}` (`getPublicLot`): a lot is public when its product is a crop of the crop registry
  (durian until a platform admin adds another), and `crop` is that code. With the new query parameter `crop_profile=1`
  the record also has `crop_name` (the registry's name in `lang`) and `ripeness_scale` (`levels_1_to_4`, or null for a
  crop graded on none, whose `ripeness` is always null); `0` or none leaves them out and any other value is 400
  `bad crop_profile`. Only a durian lot has the knocker's `measurement` journey step, a `ripeness` section and public
  fruits (`GET /v1/public/fruits/{publicId}` answers 404 for a fruit of any other lot and the lot's fruit list is
  empty): a lot of another crop, with a scale or without, has none of them. Durian always keeps its ripeness scale.
  Only a durian lot names the Durian Protocol, links a customs dossier and offers the documents issued at its seal; a
  lot of another crop is sealed without public documents.

### Application records in the lot history and the harvest app's application log (#241)

Additive: a new operation marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged), with its schemas `LotApplications` and `LotApplication`; no existing operation or schema changes.

- `listLotApplications` (`GET /v1/lots/{lot}/applications`): the company's application records (`apply` events) on
  the lot's growing area during the season before its harvest, oldest first: from 366 days (the longest interval a
  record may state after the longest application) before the lot's harvest day up to the end of that day. Accepted and
  held records are listed, a record rejected after review is not; at most 200 (`more`). A record entered by hand in
  the harvest app (`harvest_app`) is Self-declared. Same roles as `getLotSummary`; another tenant's lot, or a lot
  outside an operator's facilities, answers 404. The public record does not show these records.
- Device profile `vn.agritrace.harvest-app` 1.1.0 (`/developers/downloads/profiles/harvest-app.json`): the harvest app
  also signs `apply` records (its manual application log), with `apply.input`, `apply.product`,
  `apply.product_mass`, `apply.product_volume`, `apply.duration` and `apply.phi_days`.

### A stale pallet carton set is refused (#267)

Additive: an optional request field and a new 409 code on one operation marked `x-not-in-sdk: true` (the partner SDK
clients' generated code is unchanged).

- `PUT /v1/pallets/{sscc}/cartons` (`setPalletCartons`) takes `expected_cartons` (`PalletCartons`): the codes of every
  carton the writer read on the pallet, all lots, in any order. The server checks it inside the write, after locking
  the pallet, and refuses the set with 409 `pallet_changed` when the pallet holds other cartons, so a change made since
  that read is never overwritten; a malformed list is 400 `invalid_expected_cartons`. A refused set changes nothing
  and writes only its failed audit row (`pallet.cartons.set.failed`). A set without the field replaces what the pallet
  holds, as before. The console sends it on every save.

### Carton labels checked at the departure (#176)

One **BEHAVIOUR CHANGE** and a new trust reason code; no operation's parameters, status codes, headers or schemas
change.

- **BEHAVIOUR CHANGE**: `POST /v1/shipments/{code}/depart` (`departShipment`) takes each departing lot's carton label
  print check: every carton of the lot needs a recorded print of a ready carton label (a pallet label does
  not count) after its contents were last set, and a lot with no carton fails. If the check fails, the lot's packing
  step is lowered to Self-declared, and its tier with it, in `GET /v1/lots/{lot}/trust` and in the public lot record's
  journey. A passed check changes nothing, and a print recorded after the departure lifts nothing. The departure is
  never refused for it. A lot is not affected at packing, and a shipment that departed before this change is not
  lowered. No code list exists yet to cross-check orchard and packing house codes against, so with the default
  `require_cross_checked_codes` no export label is ready and every lot departing now fails the check. The SDK clients
  keep the operation's released description (`x-sdk-description`).
- `carton_labels_not_printed` is a new trust reason code (`GET /v1/lots/{lot}/trust` explanations), with the lot's
  cartons, those with no carton label print and those whose latest print is before their last contents change.

### Application records and the pre-harvest-interval hold (#241)

Additive: no operation or schema changes; a new event type and new capabilities for `ingestEnvelope`, and a new
quarantine reason.

- Event types vocabulary 1.3.0 (`/developers/downloads/event-types-v1.json`): `apply`, a record of an input applied to
  a growing area or parcel (water, fertiliser, pesticide, lime or light), a record only, never a command. Every event
  type names a retention class (`retention`, declared in `retentionClasses`): business events, `apply` included, are
  evidence kept at least 5 years; `observe` is telemetry.
- Capabilities vocabulary 1.3.0 (`/developers/downloads/capabilities-v1.json`): `apply.input`, `apply.product`,
  `apply.product_mass`, `apply.product_volume`, `apply.duration` and `apply.phi_days` (the pre-harvest interval the
  product label gives, in whole days). An `apply` envelope carries exactly one `apply.input` and at most one of each
  other `apply.` reading; a pesticide application names its growing area, its product and its interval, or it is held
  as `invalid_content`. No published device profile declares `apply` yet.
- A `harvest` envelope dated inside a recorded pre-harvest interval on its growing area (an `apply` record of the same
  company) is held in quarantine with the reason `pre_harvest_interval`, raises a high alert of that kind and puts its
  lot on hold until the record is reviewed (`POST /v1/envelopes/{id}/review`). An `apply` record stored after the
  harvest holds that harvest record too, even one a reviewer approved before.

### Gateway status time series (#128)

Additive: a new operation marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged), with its schemas `GatewayStatusSeries`, `GatewayStatusSample`, `GatewayStatusBucket` and
`GatewayStatusStat`; no existing operation or schema changes.

- `getGatewayStatusSeries` (`GET /v1/gateways/{id}/status-series`): a gateway's status heartbeats as a time series.
  The server stores at most one heartbeat of a gateway a minute (the first it keeps in each UTC minute of reception)
  and rolls it up by hour. `grain=minute` returns those samples (outbox depth, dead letters, link state, devices
  listed and ready); `hourly` (the default) the hourly rollups and `daily` the hourly rollups merged per UTC day (the
  number of samples; per value its minimum, maximum, mean and count; the samples per link state). Samples are kept 30
  days and hourly rollups 2 years; the range is clipped to what is kept and is at most 1 day (minute), 31 days (hourly)
  or 731 days (daily), 400 `range_too_long` beyond. Same roles as `listGateways`; another tenant's gateway answers 404.
  `getGatewayHeartbeat` still answers the newest heartbeat; a heartbeat is still never stored as an envelope.

### UNTP 0.7.0 passports, the facility record and the link set (#162)

Additive: two new anonymous operations, marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose
generated code is unchanged), and new credential contents; no existing operation's parameters, status codes or
headers change.

- The lot and fruit credentials (`getPublicLotCredential`, `getPublicFruitCredential`) of a lot sealed from now on are
  UNTP 0.7.0 Digital Product Passports (`@context` `https://vocabulary.uncefact.org/untp/0.7.0/context/`): the
  credential subject is the product, identified by its public record's URL, with `performanceClaim`,
  `relatedDocument` and `digestMultibase` links in place of 0.6.1's `product`, `conformityClaim` and
  `traceabilityInformation`. A credential sealed before keeps its UNTP 0.6.1 text, byte for byte. The operations'
  descriptions and examples say so; the partner SDK clients keep their 0.2.0 text (`x-sdk-description`,
  `x-sdk-example`).
- `getPublicLotFacilityRecord` (`GET /v1/public/lots/{publicId}/facility-record`): the packing facility's UNTP 0.7.0
  Digital Facility Record issued at the lot's seal (`PublicCredential`), linked from the lot credential; withdrawn
  (404) with it.
- `getPublicLinkset` (`GET /v1/public/linkset?code=`): the UNTP Identity Resolver link set (RFC 9264,
  `application/linkset+json`, `PublicLinkset`) of the record a code names, with the resolver's codes, 404, 410 and
  bucket. The label URLs answer the same link set when asked for `application/linkset+json`.

### The residue certificate of a lot and default limit rules per market (#157)

Additive: one new operation and two new schemas. Nothing existing changes in shape.

- `getLotResidueCertificate` (`GET /v1/lots/{lot}/residue-certificate`): every analyte the lot's lab report tested,
  with its result, the limit of the lot's destination market (its shipment's destination, else the lot's own
  destination, else the report's market), the limit's source and basis (`market_limit`, or `default_limit` for a
  market's default rule for pesticides: Japan's and Korea's 0.01 mg/kg, the EU's Art. 18(1)(b) default, the United
  States' no-tolerance rule, applied only to a pesticide a source read shows the market sets no specific limit for in
  the product), the verdict per analyte (`pass`, `fail`, `no_limit`), the analytes the destination
  market requires and those the lab did not test, whether the lab key that signed the report has been revoked for
  compromise (`report.key_revoked_for_compromise`), and an overall verdict (`pass`, `fail`, `incomplete`; never `pass`
  once the report's key is revoked for compromise, since the report then counts as unsigned). Staff only
  (tenant_admin, platform_admin acting for the tenant, auditor; the `records_export` scope for an OAuth2 token), never
  public; an audited read (`export.residue_certificate`), downloaded as an attachment.
- Behaviour: the lab step of a lot's trust is judged against the destination market's limits, its default rule and
  its lab approvals, and stops at Cross-checked while an analyte the destination market requires was not tested
  (reason `lab_required_analyte_missing`). Shipments name China only, so for every lot today the market is China and
  nothing changes.

### Sign-in with a company's own identity provider: OpenID Connect (#87)

Additive: five new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated
code is unchanged), and six new schemas. Nothing existing changes. The design and its threat model are architecture
decision record 0007 (sign-in with a company's own identity provider).

- `startOidcSignIn` (`POST /v1/auth/oidc/start`, anonymous, login rate limit): the company's identity provider's
  authorization URL (authorization code flow with PKCE S256, 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,
  encrypted (the state's SHA-256, the nonce and the code verifier; nothing is stored on the server), and binds it to the
  browser. A company without an enabled provider answers 404, the same as an unknown company. Not audited.
- `finishOidcSignIn` (`POST /v1/auth/oidc/callback`, anonymous, login rate limit): `state`, `code`, the `company` of
  the redirect URI and, when the provider sends it, `iss` (RFC 9207), from the browser that started the sign-in. The
  company must be the one the sign-in was started for, and `iss` the provider's issuer (required when the provider's
  discovery document says it sends it). The answer is 200 with a session, as login, or
  202 with a login ticket for the code step when the account has two-step sign-in. Every refusal is 401
  `identity_provider_sign_in_refused`; an unreachable provider is 502 `identity_provider_unreachable`. Audited as
  `auth.login` with `method: oidc`; a refusal is `auth.login.oidc.failed`.
- `getCompanyIdentityProvider`, `updateCompanyIdentityProvider` and `removeCompanyIdentityProvider`
  (`GET|PUT|DELETE /v1/company/identity-provider`): the selected company's provider (issuer, client id, client secret,
  on or off). Company admins and platform admins acting for the company can call them, through a signed-in session
  only. PUT and DELETE need a recent password and, for an account with two-step sign-in, the step-up. PUT checks the
  provider's discovery document first (400 `identity_provider_not_usable`). The secret is stored encrypted and never
  returned. Audited as `company.identity_provider.update` and `company.identity_provider.remove`.
- A deployment enables this with `AGRITRACE_OIDC_ALLOWED_HOSTS`, the identity provider hosts the backend may contact,
  together with `AGRITRACE_PUBLIC_ORIGIN` (each company's redirect URI is `{origin}/login/oidc/{company}`) and
  `AGRITRACE_ISSUER_KEK`.
  Without them these operations answer 503 `identity_provider_sign_in_unavailable`.

### The crop registry (#156)

Additive: six new operations for platform admins, marked `x-not-in-sdk: true` (not part of the partner SDK clients,
whose generated code is unchanged), and new schemas (`Crop`, `CropList`, `CropDetail`, `CropMarketRule`,
`CropGradingRule` and their request bodies). No existing schema changes; two existing operations refuse values they
accepted before.

- `listCrops` (`GET /v1/crops`), `createCrop` (`POST /v1/crops`), `getCrop` (`GET /v1/crops/{code}`) and `updateCrop`
  (`PATCH /v1/crops/{code}`): the crop registry (code, names in vi, en and zh-Hans, ripeness scale or none). Seeded with
  durian.
- `putCropMarketRule` (`PUT /v1/crops/{code}/markets/{market}`): a crop's registration protocol flag and sampling rule
  for a destination market. `putCropGradingRule` (`PUT /v1/crops/{code}/grading-rules`): the platform's grading rules
  for a variety of a crop, or for every variety of it.
- `createLot`/`updateLot` (`product`) and `createGrowingArea`/`updateGrowingArea` (`crop`) now refuse a value that
  names no crop of the registry and no configured crop (400 `invalid_product`, `invalid_crop`); a Vietnamese crop name
  is stored as its code (`Sầu riêng` as `durian`). Values stored before are unchanged.
- `sampleLot` (`POST /v1/lots/{lot}/samples`) refuses a lot whose crop has no sampling rule for its market (409
  `no_sampling_rule`); before, every lot was sampled under the China durian protocol. Durian lots are sampled exactly as
  before.

### EPCIS export version 2: daily sensor summaries (#238)

Additive: a new optional query parameter of `getLotEpcis` (`GET /v1/lots/{lot}/epcis`), `version`, marked
`x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is unchanged). Without it, or with
`version=1`, the document is exactly as before. Any value other than `1` or `2` is refused (400 `bad version`).

- `version=2` appends, after the lot's other events, one ObjectEvent per device and UTC day of the company's readings in
  the lot's growing area (action OBSERVE, bizStep `sensor_reporting`, read point the growing area, no objects), over
  the 31 UTC days ending with the day of the lot's harvest date, days that have ended only. Each gives the day's
  `minValue`, `maxValue` and `meanValue` per numeric capability and depth with `uom`, the counts of readings
  (`agri:readingCount`, `agri:valueCount`), the least trusted quality flag (`agri:qcFlag`) and the calibrations in force
  (`agri:calibrationId`); the sensor metadata names the device, the day and the mapping (`dataProcessingMethod`
  `agri:method/daily-summary-v2`), and links the device's metadata (`deviceMetadata`) and its telemetry envelopes
  (`rawData`) when the deployment's public origin is configured.
- The location evidence is exported, never a coordinate: `agri:geoVerdict`, `agri:geoDistM`, `agri:accM` and
  `agri:osnma` on each event.
- The audit row of the export records `version: 2` when it was asked for. The public EPCIS document of a sealed lot is
  unchanged.

### The FSMA 204 sheet carries the key data elements (#158)

Additive: the CSV of `getFsmaCsv` (`GET /v1/fsma.csv`) and `getLotFsmaCsv` (`GET /v1/lots/{lot}/fsma.csv`) keeps its
first 12 columns in their order and appends 16: `commodity`, `variety`, `field_name`, `traceability_lot_code_source`,
`traceability_lot_code_source_reference`, the shipper's and the recipient's location name, address and GLN,
`reference_document_type`, `reference_document_number`, `container`, `input_traceability_lot_code` and
`input_quantity`. The sheet also gains rows: one `shipping` row per departed shipment and lot (consignee, papers,
container, the kg of the lot's cartons on it) and one `transformation` row per lot a merge used (#91). The new
`FsmaRow` schema documents every column; it and the operations' new descriptions and header examples are not part of
the partner SDK clients (`x-not-in-sdk`, `x-sdk-description`, `x-sdk-example`), whose generated code is unchanged.
A reader that picks columns by header name, or by position among the first 12, reads the sheet as before.

### The server epoch value (#239)

Additive: a new anonymous operation, marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated
code is unchanged), and a new optional envelope context key; no existing operation or schema changes.

- `getPublicEpoch` (`GET /v1/public/epoch`): the newest signed server epoch value (`ServerEpoch`: `epoch`, `issuedAt`,
  `kid`, an ES256 `sig` and the epoch key's `publicKeyJwk`); a new value every hour. 503
  `server_epoch_value_unavailable` when none was issued in the last two hours (no `AGRITRACE_EPOCH_KEY`, or the issuing
  process stopped). Edge-cacheable like the other public reads.
- `context.epoch` in the envelope (/developers/downloads/envelope-v1.schema.json): optional. An envelope citing a
  value the server never issued, issued after a reading's time or older than 24 hours at a reading's time is still
  answered 202 `accepted` (or as before); ingest raises a `server_epoch_mismatch` alert and stores each flagged
  reading as Self-declared. Nothing new is rejected or quarantined.
- New alert kinds in `GET /v1/alerts`: `server_epoch_mismatch` and `duplicate_series` (the daily job that flags a
  sensor series repeating another one).

### The recall trace names the lots a merge links (#259)

Additive: a new optional query parameter of `getLotTrace` (`GET /v1/lots/{lot}/trace`), `merges`, and three new
`LotTrace` fields returned only with `merges=1`, all marked `x-not-in-sdk: true` (not part of the partner SDK clients,
whose generated code is unchanged). Without the parameter the trace, and the recall's answer (`recallLot`), are
unchanged. LotTrace's objects are closed (`additionalProperties: false`), so a new field there would break a client
that refuses unknown fields; these three are accepted because the server returns them only with `merges=1`, which no
client written against the earlier document sends. Any value of `merges` other than `0` or `1` is refused (400
`bad merges`).

- `forward.merged_into`: the lots holding the lot's fruit through its chain of merges, in chain order (`code`,
  `status`; at most 8), empty when no merge consumed it.
- `backward.merged_from`: the input lots of the merge that produced the lot, by code (`code`, `status`,
  `quantity_kg`, the kg the merge took from it), empty when no merge produced it.
- `forward.cartons.items[].lot`: the code of the lot each listed carton belongs to.

### Strict Content-Length on every request body (#257)

Not breaking: no operation, schema or documented response changes; a well-formed request is served as before. Every
operation that reads a request body now takes a `Content-Length` of 1 to 8 plain decimal digits, or none (an empty
body), as `postUiTelemetry` already did for its own bound (#81). A negative value (which made the server read to the
end of the stream), a sign, anything not a digit, more than 8 digits, two `Content-Length` headers, or any
`Transfer-Encoding` (a chunked body is not supported) is refused with 400 `bad_content_length` before the body is read,
with `Connection: close`; the header's value is never echoed (a non-numeric value used to be quoted in the 400 message).
`postUiTelemetry` keeps its documented 400 `invalid_beacon` "bad content length" for all of these, a chunked body and a
second `Content-Length` included.
An 8-digit value over the operation's bound is still 413.

### Corrections before the seal on the public pages (#204)

Additive: two new anonymous operations, both marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose
generated code is unchanged); `PublicLot` and `PublicFruit` are unchanged.

- `getPublicLotCorrections` (`GET /v1/public/lots/{publicId}/corrections`): per journey step (`registration`,
  `harvest`, `measurement`, and `details` for the lot's own details), how often the step was corrected before the
  lot's seal (`count`), the local date of the last correction (`last_on`) and how many came after the lot was first
  public (`after_public`), with `sealed` and `public_since` (`PublicCorrections`). Derived from the activity log's
  successful `lot.update` rows (by the fields whose value the edit changed; the destination is never counted) and
  `fruit.action` rows that override, reject or re-measure (not an acceptance, not a replay). Counts and dates only: no
  actor, value, reason or field name. The public lot's uniform 404 and 410.
- `getPublicFruitCorrections` (`GET /v1/public/fruits/{publicId}/corrections`): the same for a public fruit's page,
  its `measurement` counting that fruit's corrections only; the public fruit's uniform 404 and 410; logs no scan.

### Gateway status heartbeat (#24)

Additive: a new operation marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged), and a new kind of ingest message.

- A gateway sends a signed `status` envelope about itself (profile `vn.agritrace.gateway`, served at
  `/developers/downloads/profiles/gateway.json`; capabilities `gateway.outbox_depth`, `gateway.dead_letter_count`,
  `gateway.link` and `gateway.peripherals_ready`, capabilities vocabulary 1.2.0) to `ingestEnvelope` on
  `{tenant}/{site}/{gateway id}/status`, every 30 s by default. It is not stored as an envelope: the server keeps the
  newest heartbeat of each gateway. 202 `accepted`; 409 `duplicate` for the heartbeat kept and, with the reason
  `superseded`, for an older one. Ordering is by `seq`, except between signed heartbeats, which also compare the
  gateway's own clock: a signed heartbeat with a lower `seq` but a later time than the kept one is kept (a reset
  gateway counts its `seq` from 0 again); one with a higher `seq` but an earlier time is `superseded`; an unsigned one
  is ordered by `seq` alone. A heartbeat dated more than `max_future_skew_s` past the server clock is rejected 400
  `future_timestamp` (a device envelope gets a 202 quarantine instead). The other rejection reasons are the device
  envelopes' (`profile_mismatch`, `invalid_content`, `key_not_authorized`, `peer_mismatch`, ...).
- `getGatewayHeartbeat` (`GET /v1/gateways/{id}/heartbeat`): the gateway's newest heartbeat (`GatewayHeartbeatStatus`),
  `heartbeat` null until it sent one. Same roles as `listGateways`; another tenant's gateway answers 404.
- `createDevice` refuses the profile `vn.agritrace.gateway` (400 `invalid profile`): it describes a gateway's own
  status, never a device's.

### Correction: what a report's `scans.total` counts (#220)

Documentation only: the OpenAPI document said `getReport`'s `scans.total` counts scans that are "never deleted". Raw
scan rows are deleted 90 days after the scan (#131); `scans.total` is still the fruit's highest scan number, kept in
its scan counter, so it also counts the deleted scans and can exceed the scans `items` lists. No schema, operation or
payload changes; the partner SDK clients carry the new text from SDK 0.3.0.

### GS1 identifiers: GLN, SSCC, trade item GTINs (#161)

Additive: new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged). Numbers have 13 (GLN), 14 (GTIN) or 18 (SSCC) digits with the GS1 mod-10 check digit. `allocate: true`
(or an omitted number) takes the next number of the platform's GS1 company prefix; while none is configured the
answer is 409 `prefix_not_configured`, and a company can still enter numbers of its own GS1 membership (never numbers
under the platform's prefix, which are allocated only). Each number is unique within the company.

- `getFacilityGln`, `setFacilityGln` (`GET`, `PUT /v1/facilities/{code}/gln`): a facility's GLN; set, cleared (null)
  or allocated. Same roles as reading and editing the facility. Audited `facility.gln.set`.
- `getGrowingAreaGln`, `setGrowingAreaGln` (`GET`, `PUT /v1/growing-areas/{code}/gln`): a growing area's GLN; an
  unowned area only for a platform admin (403 otherwise). Audited `growing_area.gln.set`.
- `listProductGtins`, `createProductGtin` (`GET`, `POST /v1/product-gtins`): the GTIN of a trade item (product,
  variety, grade). Audited `product_gtin.create`.
- `listPallets`, `createPallet`, `getPallet`, `setPalletCartons` (`/v1/pallets`, `/v1/pallets/{sscc}`,
  `PUT /v1/pallets/{sscc}/cartons`): pallets of a facility identified by an SSCC, with the cartons of packed lots on
  them (409 `lot_not_packed`, `carton_on_another_pallet`, `pallet_departed`). Audited `pallet.create`,
  `pallet.cartons.set`.
- `getShipmentSscc`, `setShipmentSscc` (`GET`, `PUT /v1/shipments/{code}/sscc`): the SSCC of a shipment's container
  load, while the shipment is open (409 `shipment_departed`). Audited `shipment.sscc.set`.
- `getLotGs1Labels` (`GET /v1/lots/{lot}/gs1`): what the lot's GS1 labels print: the GS1-128 element strings
  `(01)(10)`, `(01)(10)(21)` and `(00)`, and the Digital Links. Each pallet also gives the lowest and highest number
  of the lot's cartons on it and the count of every carton it holds, so the console's export pallet label prints the
  `(00)` of the pallet that holds exactly the selected cartons. The console's export carton and pallet labels print
  these element strings, and a sealed lot's pallet label carries the lot-level Digital Link in its QR code.

Behaviour of existing operations (no schema change):

- `createLot`: a lot created without `gtin` takes the GTIN its company registered for the ungraded trade item
  (product, variety), when there is one.
- `getLotEpcis` (`GET /v1/lots/{lot}/epcis`): a facility or growing area with a GLN is named by
  `https://id.gs1.org/414/{gln}` as read point and business location: in a device event, the GLN the location had
  when the event was captured (a GLN set, changed or cleared later never changes an event already captured, and the
  outbound EPCIS delivery names the same GLNs under the same eventIDs); a pallet, load or shipping event names the
  facility's GLN in its eventID too, so another GLN gives a new event; the lot's cartons on pallets add an
  AggregationEvent per pallet (bizStep `packing`, parent the pallet's SSCC); a departed shipment with an SSCC adds the
  load's AggregationEvent (bizStep `loading`) and names the SSCC as the shipping event's EPC (that event then has a
  new eventID). Without GLNs, pallets or an SSCC the document is as before.
- The public EPCIS document issued at a later seal names an event's facility by the GLN it had when the event was
  captured (never a growing area's GLN).
- `resolvePublicCode` (`GET /v1/public/resolve`): the lot-level key `/01/{gtin}/10/{lot}` (and its element strings)
  now resolves to the lot once the lot is sealed; an unsealed lot still answers the uniform 404.

### Observability: browser beacon and more metrics (#81)

Additive: a new operation, marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged).

- `postUiTelemetry` (`POST /v1/telemetry/ui`): the web app's sampled beacon, anonymous, rate limited like the public
  routes (and by its own bucket: bursts of 10, then 2 a minute per client), a body of at most 1024 bytes
  (`UiTelemetryBeacon`: a page kind, one of `landing`, `lot`, `fruit`, `fruit_results`, `privacy`, `accessibility`
  (#84), `staff` and `other`, LCP, CLS, INP and at most 5 errors by kind and constructor name; 400
  `invalid_beacon` otherwise, 413 above the bound). 204; nothing is stored. Not audited.

Behaviour of an existing operation (no schema change; its description says so, the SDK keeps its 0.2.0 text through
`x-sdk-description`): `getMetrics` (`GET /v1/metrics`) also renders the ingest outcomes by result and reason code, the
open server-sent event streams and their cap, the outbound backlog per target and the browser beacons' histograms and
error counts (described in the operations guide).

### Lot merges (#91)

Additive: new operations, both marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged).

- `mergeLots` (`POST /v1/lots/{lot}/merge`): records that the path's draft lot was produced by merging 2 to 50 other
  lots of the company (`LotMergeRequest`: each input's `quantity_kg`, and `output_kg`), the `transform` event type of
  the event types vocabulary 1.2.0 (`/developers/downloads/event-types-v1.json`). 400 `mass_balance` when `output_kg` differs from the inputs' sum by more than 5 %
  or a packed input gives more than its packed net mass plus 5 %; 404 for an input of another company or outside an
  operator's facilities; 409 `lot_not_mergeable`, `lot_already_merged`, `lot_on_hold`, `lot_is_<status>`, and
  `lot_has_own_origin` when the output lot names a growing area, harvest date or harvest event of its own (a merged
  lot takes its origin from its inputs), and `merge_chain_too_deep` when an input is already 8 merges deep or the
  merged lot would have more than 64 merges behind it in all: the bounds a recall walks are rules of the merge, so a
  recall never stops short of the end of a chain. Audited `lot.merge`. The output lot's trust tier is at most the lowest tier
  of its inputs (reason `limited_by_input`).
- `getLotTransformations` (`GET /v1/lots/{lot}/transformations`): the merge that produced the lot and the one that
  consumed it (`LotTransformations`). For an operator limited to some facilities, a merge recorded at a facility
  outside them is not listed (as in `getLotEpcis`).

Additive refusal in an existing operation:

- `updateLot` (`PATCH /v1/lots/{lot}`) answers 409 `merged_lot_origin` when it would set `growing_area`,
  `harvest_date` or `harvest_event_id` on a lot a merge produced; clearing them is still accepted.

Additive in existing responses:

- `getLotEpcis` lists a TransformationEvent (bizStep `repackaging`, input and output lots with their kilograms) for
  each merge the lot took part in.
- The records export (`getLotRecordsExportJson`, `getLotRecordsExportCsv`, `getRecordsExportJson`,
  `getRecordsExportCsv`) may return the row kind `transformation_input` and the critical tracking event
  `transformation`. The SDK clients keep the 0.2.0 enums and descriptions through `x-sdk-enum` (new) and
  `x-sdk-description`.
- The recall export (`getLotRecallExportJson`, `getLotRecallExportCsv`) follows the chain of lot merges (a merged
  lot can be closed and merged again): it may return the critical tracking event `transformation` (one row per input
  lot and one of the lot produced), the harvest rows of the inputs of every merge backward (breadth first, at most 8
  levels and 64 merges) and the packing and shipping rows of every lot the fruit went into forward (at most 8 merges),
  each with that lot's code; `RecallExport.rows` may hold up to 186,855 rows. `getLotTrace` counts and lists, in
  `forward`, the cartons of every lot holding the lot's fruit through the chain (at most 8 merges, in chain order),
  and gives the first shipment found along the chain, the lot's own first. A shipped lot can be merged again, so a
  chain may hold several shipments: `recallLot` counts every distinct one in `LotRecall.shipments` (and the
  `lot.recalled` and `lot.withdrawn` webhooks' `shipments`), and the stored outbound notice lists them all. The SDK
  clients keep the 0.2.0 enum, bound and descriptions through `x-sdk-enum`, `x-sdk-maxItems` (new) and
  `x-sdk-description`.
- `limited_by_input` is a new trust reason code (`GET /v1/lots/{lot}/trust` explanations).

### The lab's identity and its UNTP Conformity Credential (#142)

Additive: new anonymous operations, both marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose
generated code is unchanged).

- `getLabDidDocument` (`GET /labs/{code}/did.json`): a lab's DID document, `did:web:<domain>:labs:<code>`, served at
  the root of the issuer host like a facility's (`/{slug}/did.json`). It lists the lab's keys that are active or were
  revoked for a rotation, never one revoked for compromise; 404 like the facility document otherwise.
- `getPublicLotLabCredential` (`GET /v1/public/lots/{publicId}/lab-credential`): the UNTP Digital Conformity
  Credential 0.6.1 that the lab issues for its report on a sealed lot, a compact JWS (`application/vc+jwt`,
  `PublicConformityCredential`) that verifies with the lab's DID document. It exists only for a report the lab entered
  in its CropPath portal (signed with the key CropPath holds for the lab's portal users); 404 like the lot's other
  downloads otherwise, and once the lab key that signed it is revoked for compromise; 410 for a removed lot.

Behaviour of existing operations (no schema change): in the lot credential (`getPublicLotCredential`) issued from now
on, each lab claim of such a report carries `conformityEvidence`, a link to that credential with its SHA-256.

### Grower consent records and grower data requests (#163)

Additive: new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged), for a signed-in session of a company admin (or a platform admin acting for the company) only.

- `listGrowerConsents` (`GET /v1/growers/{id}/consents`): the grower's consents in force (`in_force`) and its consent
  records, newest first (`GrowerConsentPage`).
- `recordGrowerConsent` (`POST /v1/growers/{id}/consents`): appends a grower's decision, `granted` or `withdrawn`, for
  `public_name` or `orchard_position`, one market or every market (`market` null), with how it was captured; a grant
  needs `paper` or `electronic` evidence and its SHA-256. 409 `already_granted` or `not_granted` when the decision
  does not change what is in force. The public fruit page names the grower with the public-name consent for the
  destination market of the shipment its lot is on, or else for every market; a withdrawal takes it off at once.
  `in_force[].evidence_recorded` is false for a grant without an evidence hash. A withdrawal stays open while the
  company leaves CropPath and, for a platform admin, after it has left; a grant is refused 403 `company_read_only`
  then. Audited `grower.consent.record`.
- `listGrowerDataRequests` (`GET /v1/grower-data-requests?status=&grower_id=`), `createGrowerDataRequest`
  (`POST /v1/grower-data-requests`) and `handleGrowerDataRequest` (`POST /v1/grower-data-requests/{id}/handled`): a
  grower's request (`access`, `rectification`, `erasure`, `objection`) as the company received it, due 30 days after
  the day received, answered once (409 `already_handled`); an erasure or an objection can withdraw every consent in
  force (`withdraw_public`). Open during a departing company's read-only window. Audited `grower_data_request.create`
  and `grower_data_request.handle`.

Behaviour of existing operations (no schema change; their descriptions say so, the SDK keeps its 0.2.0 text through
`x-sdk-description`): `createGrower` and `updateGrower` also append a consent record (channel `record_edit`) when they
turn `public_consent` on or off.

Planned deprecation: granting the public name through `public_consent` (`createGrower`, `updateGrower` and the grower
batch) records no evidence, so it bypasses the rule that a grant needs written evidence. It stays for SDK 0.2.0
compatibility; such a grant is shown to staff as "no evidence recorded", and the console grants only through
`recordGrowerConsent`. The next minor SDK release is to mark turning `public_consent` on as deprecated in favour of
`recordGrowerConsent`, with a sunset date announced here; turning it off (a withdrawal) stays.

### Second admin approval for critical company actions (#203)

Additive: new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged), for a signed-in session of a company admin (or a platform admin acting for the company) only.

- `getCompanyFourEyes` and `updateCompanyFourEyes` (`GET|PUT /v1/company/four-eyes`): the company's
  `require_second_admin` setting (`FourEyesState`: also its active admins and the requests waiting). Turning it on
  needs a recent password; turning it off while it is on is itself a critical action. Audited
  `company.four_eyes.update`.
- `listApprovalRequests` (`GET /v1/approval-requests?status=pending|all`) and `createApprovalRequest`
  (`POST /v1/approval-requests` with the action's `method`, `path` and `body`; a recent password). At most 20 wait at
  a time; a request may be decided for 72 hours (then `expired`). Audited `approval_request.create` (the action and
  the expiry, never the body).
- `approveApprovalRequest` (`POST /v1/approval-requests/{id}/approve`; a recent password and the step-up) runs the
  action exactly as if the approver had called it directly, once, in the action's transaction with the action's own
  audit row and `approval_request.approve` (an issuer key the store cannot create: the action's own 503);
  `rejectApprovalRequest` (`POST /v1/approval-requests/{id}/reject`, optional `reason`; a recent password and the
  step-up) runs nothing (`approval_request.reject`). The admin who asked gets 403 `same_admin`; a decided or expired
  request 409; another company's 404. A platform admin decides as CropPath support (`decided_as`
  `platform_support`): the second approver of a company with one admin only; for a company with two or more admins
  403 `company_has_second_admin`.

Behaviour of existing operations (no schema change; their descriptions say so, the SDK keeps its 0.2.0 text through
`x-sdk-description`): while a company requires a second admin, `createKey` (`POST /v1/keys`), `approveHarvestKey`
(`POST /v1/harvest-keys/{kid}/approve`), `createIssuerKey` (`POST /v1/facilities/{code}/issuer-keys`),
`putGradingRules` (`PUT /v1/grading-rules/{variety}`) and `updateCompanySecurity` (`PUT /v1/company/security`)
answer 403 `second_admin_approval_required` before anything is done (no audit row, no Idempotency-Key used). A
company that does not turn the setting on sees no change. There is no recall cancellation to guard: a recall is
terminal. Migration 80: `company_settings.require_second_admin` and `approval_requests`.

### Passkeys (#87)

Additive: new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged). They need AGRITRACE_PUBLIC_ORIGIN (the Relying Party); without it they answer 503
`passkeys_unavailable`.

- `listMyPasskeys` (`GET /v1/auth/passkeys`): the signed-in user's own passkeys (`Passkey`): nickname, algorithm,
  transports, attestation format, when added and last used, `clone_warning_at`. Never a credential id or key.
- `startPasskeyRegistration` (`POST /v1/auth/passkeys/registration-options`) and `registerPasskey`
  (`POST /v1/auth/passkeys`): navigator.credentials.create() options with a single-use challenge (5 minutes), then
  its answer, verified per WebAuthn Level 2 (ES256, RS256 or EdDSA; user verification required; attestation `none`).
  Both need a recent password. At most 10 per account (409 `too_many_passkeys`); 409 `passkey_already_registered`.
  Audited `auth.passkey.register`.
- `renamePasskey` (`PATCH /v1/auth/passkeys/{id}`, audited `auth.passkey.rename`) and `removePasskey`
  (`DELETE /v1/auth/passkeys/{id}`, audited `auth.passkey.remove`; needs the step-up: a recent password and, with
  two-step sign-in, a code or a passkey sign-in within 5 minutes). Another user's passkey answers 404.
- `startPasskeySignIn` (`POST /v1/auth/passkeys/authentication-options`) and `signInWithPasskey`
  (`POST /v1/auth/passkeys/login`): anonymous, login rate-limit bucket. The session it opens counts as having proved
  the password and a second factor: it satisfies two-step sign-in and the step-up of the operations above. Audited
  `auth.login` (`second_factor: passkey`); every refusal is 401 `invalid_passkey` (`auth.login.passkey.failed`).
- Migration 78: `passkeys` and `webauthn_challenges`.

### Step-up MFA for key revocation, recalls and market limits (#87)

Additive: no new operation, no schema change. A signed-in session of an account with two-step sign-in now needs a
code (or backup code) confirmed within the last 5 minutes, and its password within the last 10, for `revokeKey`
(`POST /v1/keys/{kid}/revoke`), `revokeLabKey` (`POST /v1/labs/{code}/keys/{kid}/revoke`), `revokeIssuerKey`
(`POST /v1/facilities/{code}/issuer-keys/{key}/revoke`), `recallLot` (`POST /v1/lots/{lot}/recall`, recall and
withdrawal) and `createMarketLimit` (`POST /v1/market-limits`); otherwise they answer 401 `mfa_step_up_required`
before anything is done (no audit row, no Idempotency-Key used). Confirm both with `reauthenticate`
(`POST /v1/auth/reauth`, `password` with `code` or `backup_code`), then repeat the request. Sessions of accounts
without two-step sign-in, API tokens and API clients are served as before. The descriptions say so; the SDK keeps its
0.2.0 text through `x-sdk-description`.

### Tighter API client credentials (#205)

Additive: new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code
is unchanged), for a signed-in session of a company admin only.

- `listOAuthClientDetails` (`GET /v1/oauth-clients/details`): the clients with their expiry (`expires_at`,
  `expired`), allowed source networks (`allowed_ips`), last use (`last_used_at`, `last_used_ip_hash`: a keyed hash,
  never the address) and write scopes (`write_scopes`, `broad_scope`) (`OAuthClientDetail`).
- `renewOAuthClient` (`POST /v1/oauth-clients/{id}/renew`): a new expiry, `expires_in_days` (1 to 730, default 365)
  from now. 409 `client_revoked` for a revoked client. Needs a recent password. Audited `oauth_client.renew`.
- `setOAuthClientAllowedIps` (`PUT /v1/oauth-clients/{id}/allowed-ips`): 1 to 20 IPv4 or IPv6 networks in CIDR form,
  or null for any source. Needs a recent password. Audited `oauth_client.allowed_ips` (a count and a keyed hash, an
  HMAC under the server's hash secret, of the list; never the networks).

Behaviour of existing operations (no schema change; their descriptions say so, the SDK keeps its 0.2.0 text through
`x-sdk-description`):

- Every client now expires: 365 days after `createOAuthClient`, and 365 days after the upgrade for clients registered
  before it. `oauthToken` and `oauthRevoke` answer `invalid_client` for an expired client and for a client called from
  a source outside its allowed networks, and that client's access tokens answer 401 `missing_or_invalid_token`.
- `revokeOAuthClient` marks the client's live access tokens revoked in the same transaction; its audit row holds how
  many (`tokens_revoked`). The `oauth_client.create` audit row also holds `expires_at` and `broad_scope`.

### Lot events read audited (#108)

Additive: `listLotEvents` (`GET /v1/lots/{lot}/events`) is now an audited read like the other exports: each answered
request writes one row in the company's activity log (`export.events`, entity `lot`, the lot code; the status only,
never the envelopes), and while the server is in read-only maintenance it answers 503 with `Retry-After` like them.
The response and the OpenAPI document are unchanged. It is audited because it answers the lot's stored event records in
full, the same records its EPCIS document and FSMA 204 sheet are built from.

### Correction: the `lot.withdrawn` webhook example (#181)

Documentation only: the OpenAPI document's example body of the `lot.withdrawn` event (on the webhook and on its
`WebhookEventLotWithdrawn` schema) showed `data.kind` `recall`; a withdrawal event always carries `withdrawal` (and
`lot.recalled` always `recall`), as the webhook guide already showed. No schema, operation or payload changes, and
the partner SDK clients' generated code is unchanged.

### Growing-area sensor series and verdict map (#235)

Additive: new read operations, both marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated
code is unchanged). Neither writes anything, so neither is audited.

- `getSensorSeries` (`GET /v1/growing-areas/{code}/sensor-series?capability=&depth_cm=&grain=&from=&to=`): the hourly
  or daily summaries of one vocabulary capability in the growing area from the caller's company's devices, one series
  per depth (`SensorSeries`): per bucket the minimum, maximum, mean (null when no value counted) and count of the values
  flagged pass or not evaluated, every reading's count and the count per QC flag. 400 for a missing or unknown
  capability (`capability_is_required`, `unknown_capability`), a bad grain, depth or time, or a range longer than 31
  days hourly or 5 years daily (`range_too_long`); at most 5000 buckets an answer (`truncated`).
- `getVerdictMap` (`GET /v1/growing-areas/{code}/verdict-map?from=&to=`): the devices bound to the area or judged
  against it over at most 31 days of reception times, with their current placement, geofence verdict counts and latest
  verdict (`VerdictMap`). The install point and the latest judged position only for a platform admin and the
  operators and tenant admins of the area's owning company (`coordinates_shown`); the boundary only to whom the
  growing-area read gives it. Never public.

Both allow platform_admin, tenant_admin, auditor and operator (the growing-area read policy); another company's area
answers 404.

### Low-kit field sensor profiles (#231)

Additive: three device profiles the server knows, so `createDevice` accepts them as `DeviceCreate.profile`:
`vn.agritrace.soil-rs485-4in1-ec` (soil probe with an EC channel), `vn.agritrace.air-th-xy-md02` (air temperature and
humidity) and `vn.agritrace.rain-ub-ra-n1` (rain gauge), each served as a file below
`/developers/downloads/profiles/`. Only the description of `DeviceCreate.profile` changes. The partner SDK clients
keep the description they were released with (`x-sdk-description`), so their generated code is unchanged.

### Sensor calibrations and device metadata (#234)

Additive: new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged).

- `recordDeviceCalibration` (`POST /v1/devices/{id}/calibrations`): records a calibration of one of the company's
  devices (`CalibrationCreate`): the probe serial and the capability it covers (optional), when it was done, the method
  (`ph_buffers`, `ec_reference`, `lab_correlation`, `factory`, `other`), the reference values and coefficients (small
  JSON values), the performer and its accreditation (`iso17025_lab`, `in_house`, `manufacturer`), the certificate and
  `valid_until`. The certificate is uploaded first with `PUT /v1/attachments/{sha256}` and named by
  `certificate_sha256`, or sent in `certificate` (base64), whose bytes must hash to `certificate_sha256` (400
  `certificate_hash_mismatch`). Calibrations are never edited: a correction names the calibration it corrects in
  `supersedes` (409 `calibration_superseded` when that one is corrected already). Allowed for tenant_admin and
  platform_admin acting for the company (and an API client with `device_admin`); audited as `device.calibration`.
- `listDeviceCalibrations` (`GET /v1/devices/{id}/calibrations`, optional `sensor_serial`): the device's calibrations,
  newest first, each with the calibration that supersedes it (`superseded_by`); the roles that read the device. Who
  recorded a calibration (`Calibration.created_by`) is answered to platform admins only, here, in the answer of
  `recordDeviceCalibration` and in `getDeviceMetadata`, as a placement's `recorded_by`.
- `getDeviceMetadata` (`GET /v1/devices/{id}/metadata`): the device's placement version in force and its calibrations
  not superseded (`DeviceMetadata`), for the device's company and platform admins acting for it, never public; another
  company's device answers 404. It is the document an EPCIS `deviceMetadata` link can name later; EPCIS exports do not
  link it yet.
- Readings: each reading of a device with calibrations is linked to the calibration in force at its time (the latest
  not superseded, made at or before it, covering its capability or every capability of the device). A reading made
  after that calibration's `valid_until` gets the new QC test `calibration` as suspect (QC flag 3, reason
  `calibration_expired`), which a failed test still outranks; without any calibration the test is not evaluated.

### Boundary walks (#248)

Additive: new operations, all marked `x-not-in-sdk: true` (not part of the partner SDK clients, whose generated code is
unchanged).

- `submitBoundaryWalk` (`POST /v1/growing-areas/{code}/boundary-walks`): someone of the company walked the edge of the
  growing area with a phone. The outline (`BoundaryWalkCreate.polygon`: a Polygon of one ring) becomes the area's
  pending boundary proposal, approved or rejected in the boundary proposal queue like a company admin's boundary change
  (#224); it never changes the boundary in force, whoever sends it and whether or not the area is approved, and it
  replaces a proposal that was waiting. Approving the proposal records a boundary version; it does not approve the
  area. The server refuses an outline with fewer than 3 different corners (`too_few_corners`), crossing itself
  (`self_intersecting`), under 0.01 ha (`too_small`) or with a corner that is not one of the submitted points within
  the accuracy threshold (`vertex_not_walked`), and answers the walked area (`BoundaryWalkResult`). Idempotent on the
  area and `client_walk_id`: the same walk sent again answers 200 with the stored result, another walk with the same id
  409 `client_walk_id_taken`. Allowed for operator, tenant_admin and platform_admin acting for the company, never an
  OAuth client; audited as `growing_area.boundary_walk.submit` (the walk, the outline's SHA-256 and the counts, never
  the track).
- `listBoundaryWalks` (`GET /v1/growing-areas/{code}/boundary-walks`, optional `polygon_sha256`) and `getBoundaryWalk`
  (`GET /v1/growing-areas/{code}/boundary-walks/{id}`, with the outline and the raw track): the walks kept as the
  evidence of the proposal and version with the same `polygon_sha256`, for the area company's tenant_admin and
  platform_admin only; never public.

### Growing-area boundary lock and versions (#224)

Additive: new operations; a company admin's boundary change of an approved area now waits for CropPath.

- `PATCH /v1/growing-areas/{code}` (`updateGrowingArea`): once a platform admin has approved the area, a
  tenant_admin's `polygon` is no longer applied. Unless it equals the boundary in force, it is stored as the area's
  boundary proposal (replacing an earlier one) and the response keeps the boundary in force; sending the boundary in
  force again withdraws the waiting proposal. The other fields of the same request apply as before. Before the area's
  first approval, and for a platform_admin, `polygon` applies at once as before; a platform_admin's change of the
  boundary supersedes (clears) the company's waiting proposal. The activity log row (`growing_area.update`) names the
  proposal's SHA-256 (`polygon_proposed`), and the SHA-256 and time of a proposal withdrawn
  (`polygon_proposal_withdrawn`) or superseded (`polygon_proposal_superseded`), never coordinates.
- Every boundary CropPath approves is kept as an immutable, numbered version (`PolygonVersion`: `version`, the SHA-256
  of its canonical GeoJSON text, `valid_from`, `origin`), recorded when the area is approved
  (`approveGrowingArea`), when a proposal is approved, or when a platform admin changes the boundary; versions are
  never changed, and are deleted only with their growing area (the database refuses any other deletion). The boundaries of areas approved before this change are their version 1 (`origin`
  `migration`), in force from the area's last change.
- `listPolygonVersions` (`GET /v1/growing-areas/{code}/polygon-versions`): the waiting proposal and the versions,
  newest first. The owning tenant_admin and platform_admin get the boundaries and who proposed and approved them;
  other readers the SHA-256 and times only.
- `listPolygonProposals` (`GET /v1/polygon-proposals`: each waiting change with the boundary in force,
  `current_polygon`, for comparison), `approvePolygonProposal`
  (`POST /v1/polygon-proposals/{code}/approve`, `{"polygon_sha256"}`: the SHA-256 of the proposal reviewed, 409
  `polygon_proposal_changed` when the company replaced it meanwhile) and `rejectPolygonProposal`
  (`POST /v1/polygon-proposals/{code}/reject`, `{"reason"}`): the platform's queue and decisions, platform_admin only,
  audited as `growing_area.polygon.approve` and `growing_area.polygon.reject` in the area's company's activity log.
- `x-not-in-sdk: true` marks the four new operations: they are not part of the partner SDK clients (SDK 0.2.0 was
  released before them), so the SDKs' generated code is unchanged.

### Changed: device placements, and approving a device needs one (#225)

**BEHAVIOUR CHANGE** for a platform-admin-only operation: `approveDevice` (`POST /v1/devices/{id}/approve`) now
answers **409** `placement_required` (standard `Error` body, `{"error": "placement required: record where the device
is installed before approving it", "code": "placement_required"}`) when the device's current placement version is not
an installation (no placement recorded yet, or the device was taken out). Nothing changes and the refusal is one audit
row (`device.approve.failed`). An already approved device keeps its approval. The new operations below are added.

- `listDevicePlacements` (`GET /v1/devices/{id}/placements`): every placement version of a device of the company,
  newest first. Same roles as reading the device; `recorded_by` is returned to platform admins only.
- `recordDevicePlacement` (`POST /v1/devices/{id}/placements`): platform admin only, acting for the device's company
  (`X-Tenant`). Records a new version: an installation (`fixed` with its growing area, install point and commissioning
  record, or `mobile`) or a removal (`removed_at`). A version is never changed; one audit row each
  (`device.placement`). 409 when it starts before the current version or there is no installation to remove.
- Both are `x-not-in-sdk`: not part of the partner SDK 0.2.0 clients.
- Ingest: an envelope of a device whose placement in force at its time is `fixed` and claims another growing area is
  quarantined as `growing_area_mismatch`; while the removal of a fixed installation is in force it is quarantined as
  `growing_area_mismatch` (another area) or `device_removed` (that installation's area), with a `device_removed`
  alert.

### Company profile: household businesses and the public customs file (#208)

Additive: a new operation pair; no existing schema changes (`CompanyProfile` and `CompanyProfileUpdate` stay exactly
as SDK 0.2.0 decodes and sends them).

- New: `getCompanyPublicIdentity` and `putCompanyPublicIdentity` (`GET` and `PUT /v1/company/profile/public-identity`),
  with the same access as the profile (admins, auditors and operators read; company admins and a platform admin
  through `X-Tenant` write). The body (`CompanyPublicIdentityUpdate`) holds three required flags, each `true` or
  `false`: `household_business` (the company is a household business, hộ kinh doanh), and its two opt-ins
  `public_full_address` and `public_legal_name`, which apply to a household business only and are stored `false` for
  a company. Another value, a missing flag or another member is a 400 (`invalid_<flag>`, `unknown_field`); a company
  that has not saved its profile yet gets a 409 `no_company_profile`. The answer (`CompanyPublicIdentity`) holds the
  three flags (`false` until set) and `public_producer` (a `CompanyProducer`, null until the profile is saved): the
  producer as the lot's public customs file shows it now. Audited as `company.public_identity.update`: the prior
  profile's hash and the names of the flags that changed, never a value.
- Saving the profile (`putCompanyProfile`) never changes the flags, so a client that does not know them (SDK 0.2.0,
  or a console tab still on the earlier build) never turns a household business back into a company.
- The new operations are marked `x-not-in-sdk: true`: the published SDK 0.2.0 packages do not carry them and their
  bytes do not change. Call them over HTTP; a later SDK version will add them.
- `getPublicLotCustomsDossier` and `getPublicLotCustomsDossierPrint`: for a household business, `producer.legal_name`
  holds its trading name (or `Hộ kinh doanh` alone when it has no trading name: never the owner's personal name, and
  never the tax number, which for a household business is the representative's personal identification number) and `producer.address` and `producer.district` are null (the province and country
  stay), unless it opted in to its legal name or its full address. A company's `producer` is unchanged, as are the
  members and their types. The export labels (`ExportLabel.fields.producer`), the company's export and the profile
  itself keep the full legal name and address.
- Company export (`profile.json`): `profile` adds `household_business`, `public_full_address` and `public_legal_name`
  (`true` or `false`).
- The breaking-change check ([versioning.md](versioning.md)) now counts a new field of a response object the document
  closes (`additionalProperties: false`) as breaking: a client generated from it may refuse a field it does not know
  (the Go SDK does).

### Public reads: 410 `lot_removed` for a lot deleted at its retention end (#209)

Additive: a new response on existing operations; every other answer is unchanged.

- `getPublicLot`, `getPublicLotCustomsDossier`, `getPublicLotCustomsDossierPrint`, `getPublicLotEpcis`,
  `getPublicLotCredential`, `getPublicLotAnchorProof`, `listPublicLotFruits`, `getPublicFruit`,
  `getPublicFruitCredential`, `getPublicFruitRecording` and `resolvePublicCode` answer **410** with the standard
  `Error` body, `{"error": "lot removed: this record is no longer available", "code": "lot_removed"}`, for the public
  id of a lot, or the public id or GS1 serial of a fruit or carton of a lot, that CropPath deleted when the retention
  period of a company that left CropPath ended (the shared response `LotRemoved`; `Cache-Control` as a 404). Only the
  code and the date it was removed are kept, so the answer says nothing else about the lot. A code that never named a
  record still answers 404.
- A departed company's activity log shows the deletion: `company.retention.lot_deleted` (entity `lot`) and
  `company.retention.records_deleted` (entity `company`), actor `system:retention` (kind `server`).

### Hosted sandbox: `POST /v1/sandbox/accounts` (#218)

Additive: a new operation that exists on the hosted sandbox only; every other deployment answers it exactly as before
(404 `no_such_route`, like any unknown path).

- `createSandboxAccount` (`POST /v1/sandbox/accounts`, tag `sandbox`, no security): on the hosted sandbox, creates a
  fresh demo company (`tenant_id`, `sbx-` and 16 random characters), seeded with the demo scenario within a few
  minutes, and returns once a 24-hour API token for it (`api_token`, role tenant_admin of that company only),
  `expires_at` and `base_url` (`SandboxAccount`). The body is empty or `{}` (`SandboxAccountCreate`). 429 with
  `Retry-After` past 5 accounts an hour per client address, 503 `sandbox_full` at 500 live sandbox companies (both the
  sandbox's settings); the company and all its data are deleted 7 days after its creation.
- `x-sandbox-only: true` marks it, in the style of `x-session-only`: an operation of the hosted sandbox only, which
  answers 404 `no_such_route` for every method on every other deployment.

### Documentation: descriptions name the developer portal's files (#212)

Additive (wording only): no request is answered differently.

- Descriptions that named files of CropPath's source code now name the files the developer portal serves:
  `/developers/downloads/company-export.md` (`downloadCompanyExport`, `CompanyExport`), `epcis-capture.md`
  (`captureEpcis`), `verify.md` (`getPublicLotCredential`, `PublicCredential`), `integrity-anchors.md` and
  `verify_anchors.py` (`listPublicAnchors`, `getPublicLotAnchorProof`, `IntegrityAnchor`, `AnchorInclusionProof`).
- `Envelope`, `StoredEnvelope`, `ingestEnvelope` and `listLotEvents` name the envelope version (`spec`
  `agritrace.iot/1.0`). `Envelope` and `ingestEnvelope` name the device contract the portal now serves: the
  envelope schema at `/developers/downloads/envelope-v1.schema.json`, the event types at
  `/developers/downloads/event-types-v1.json`, the capabilities at `/developers/downloads/capabilities-v1.json` and
  the device profiles below `/developers/downloads/profiles/`. `StoredEnvelope` names the envelope schema
  (`/developers/downloads/envelope-v1.schema.json`) and the event types (`/developers/downloads/event-types-v1.json`).
  `DeviceCreate.profile` lists every profile id the server accepts, each with its served file.
- `PublicCustomsDossier`, `TrustTier` and `PublicEpcisDocument` no longer point at internal documents (a decision
  record, the domain model and the test copy of GS1's schema); their meaning is unchanged.

### Correction: session-only operations, servers and tags (#213)

Breaking on paper, accepted as a correction: no request is answered differently.

- 49 operations whose handler refuses an API token, an API client and the legacy token (403 `role_not_permitted`)
  listed `bearer` beside the session cookie: proposing a facility, API tokens and API clients, members and
  invitations, the company's two-step sign-in rule, getting-started checklist, usage, data export and offboarding
  state, notifications, personal data and its requests, support requests, the platform's support queue and
  announcements, the platform's first-admin and recovery links, and starting or cancelling a company's offboarding.
  Their `security` now lists the session cookie alone, so a client generated from the document no longer offers a
  bearer credential for them.
- `x-session-only: true` marks every operation only a signed-in session may call: these 49 and the 12 session routes
  (`/v1/auth/...` of the signed-in user and `GET /v1/help`). An API token or API client calling one of the 12 is
  refused with 401 `not_authenticated` (they read only the session cookie).
- New top-level `servers` (`https://txng.theio.vn`), a description of the API for partners, and `tags` with a
  description for each of the 20 tags. The Go SDK's generated configuration names that server by default;
  `croppath.New` still uses the base URL it is given.
- Request examples for `approveDevice`, `rejectDevice`, `approveGateway` and `rejectGateway`.
  `GET /v1/lots/{lot}/events`, `/epcis`, `/fsma.csv` and `GET /v1/volumes/{growing_area}/{season}` now say what they
  have always done: a lot code that is not the company's, or an unknown area, answers 200 with an empty result,
  never 404.

### Added: a member's own personal data and their requests about it (#198)

Additive.

- `GET /v1/account/personal-data` (`getMyPersonalData`, `PersonalData`): what the platform holds about the caller in
  the selected company: name, email, roles (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 5 most recent
  sign-ins. Never a secret.
- `POST /v1/account/personal-data-requests {kind, text}` (`createPersonalDataRequest`, `PersonalDataRequestCreate`,
  `PersonalDataRequest`): ask the company's admins to show more (`access`) or correct (`correction`) the caller's
  personal data; plain text of 1 to 2,000 characters; at most 5 per person per day (across companies) and 50 per
  company per day (429 with code `too_many_personal_data_requests` for the person's limit and
  `too_many_personal_data_requests_company` for the company's). Audited `personal_data_request.create` (never the
  text).
  `GET /v1/account/personal-data-requests` (`listMyPersonalDataRequests`): the caller's own requests in the company.
  These three: tenant_admin, operator and auditor through a signed-in session only; API tokens, API clients, lab users
  and platform admins get 403. Not an OAuth scope.
- `GET /v1/personal-data-requests?status=` (`listCompanyPersonalDataRequests`, `CompanyPersonalDataRequestPage`) and
  `POST /v1/personal-data-requests/{id}/handled` (`markPersonalDataRequestHandled`): the company's admins list the
  requests with who sent them and mark one handled (final; 409 `already handled`; audited
  `personal_data_request.handle`). Team management: tenant_admin and platform_admin through a signed-in session only;
  another company's request answers 404.

### Added: in-app notifications for company admins (#195)

Additive.

- `GET /v1/notifications?unread=&cursor=&limit=` (`listNotifications`, `NotificationPage`): the caller's own
  notifications in the company it acts for, newest first (limit 1 to 100, default 20), with the unread count. Each is a
  `kind` (`NotificationKind`) and its `params` (`NotificationParams`: identifiers, names and times, never rendered
  text): 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. No email. Read notifications are deleted
  90 days after they were created.
- `GET /v1/notifications/unread-count` (`getNotificationUnreadCount`): the bell's badge.
- `POST /v1/notifications/{id}/read` (`markNotificationRead`) and `POST /v1/notifications/read-all`
  (`markAllNotificationsRead`, `NotificationsMarkedRead`): another user's or another company's notification answers
  404. Not audited: they change only the reader's own view of their list.
- All four: tenant_admin and platform_admin (acting for the company) through a signed-in session only; an API token,
  an API client or the legacy token is refused (403). The two POSTs take `Idempotency-Key`.

### Added: company offboarding (#193)

Additive.

- `POST /v1/tenants/{id}/offboarding {retention_years}` (`startCompanyOffboarding`, `CompanyOffboardingStart`,
  `CompanyOffboarding`): a platform admin marks a company as leaving CropPath. `retention_years` (1 to 30, no
  default; 400 `invalid_retention_years`) is how long its sealed lot records, evidence and public lot pages stay,
  counted from each lot's seal. A 30-day read-only window starts; 409 `already_leaving`, `already_left` or
  `platform_company`; 404 for an unknown company. Audited `company.offboarding.start` in the company's log.
- `POST /v1/tenants/{id}/offboarding/cancel` (`cancelCompanyOffboarding`): cancels the departure during the window
  (409 `not_leaving` or `already_left`). Audited `company.offboarding.cancel`. Both platform_admin through a signed-in
  session only, with a recent password confirmation (401 `reauthentication_required`); both take `Idempotency-Key`,
  so they join the Go, Java and .NET SDKs' keyed POST lists.
- `GET /v1/company/offboarding` (`getCompanyOffboarding`): the selected company's state (`active`, `leaving` with
  `window_ends_at`, or `left`), for the company's tenant_admin, operator and auditor members and platform_admin
  through a session (policy `company_state_read`, not delegable to an API client).
- `Tenant` (`GET /v1/tenants`, `POST /v1/tenants`) gains `offboarding`, the company's state.
- While a company is leaving and after it left, every other write for that company answers 403
  `company_read_only` (documented in each write's 403); reads and `POST /v1/company/exports` keep working. Its device
  messages are rejected with the new reason `company_read_only` (403 on `POST /v1/ingest/...`). A write that changes
  another company's record checks that record's company, whatever company the caller acts for: a lab result, portal
  entry or report PDF for a sampling of such a company (`/v1/lab/samples/{id}/...`), and a platform admin's decision
  on its facility proposals, devices or gateways, answer 403 `company_read_only`, while a lab user or platform admin
  whose own company is leaving still acts on other companies' records. `POST /v1/public/reports` on a fruit of such a
  company answers the new response 403 `company_read_only` (nothing stored), and so does a device's attachment upload
  for an envelope of such a company (`PUT /v1/devices/{id}/attachments/{sha256}`, 403 `company_read_only` beside
  `peer_mismatch`; nothing stored). Once the company has left,
  `POST /v1/tenants/{id}/admin-invitations` and `POST /v1/tenants/{id}/admins/{user_id}/recovery-link` answer 409
  `company_left`.
- With the other Phase 2 routes: `POST /v1/members/{user_id}/unlock` and `POST /v1/members/{user_id}/sessions/revoke`
  of such a company answer 403 `company_read_only`. CropPath support and personal data requests stay open during the
  read-only window: `POST /v1/support-requests`, `POST /v1/account/personal-data-requests` and
  `POST /v1/personal-data-requests/{id}/handled` work as before, and answer 403 `company_read_only` once the company
  has left; `PATCH /v1/platform/support-requests/{id}` checks the request's company (403 `company_read_only` once it
  has left, whatever company the platform admin acts for). `POST /v1/notifications/{id}/read` and `POST /v1/notifications/read-all` (the reader's
  own view) and the platform-wide `POST /v1/platform/announcements` and `.../{id}/expire` keep working, like the reads,
  `GET /v1/company/usage` and the account's own sessions (`/v1/auth/sessions/...`).
- After the window the background job stops sign-in for the company (a lab user's membership stays), revokes its API
  tokens, API clients and webhooks and removes its people's names and emails everywhere but the activity log and the
  reviewer of a quarantined envelope (both covered by the integrity anchors): the company's in-app notifications,
  personal data requests and support requests are deleted (the `company.offboarding.personal_data_removed` row's
  `after` reports them as `rows_deleted`, apart from `references_replaced`); its
  audit rows (`company.offboarding.members_off`,
  `company.offboarding.credentials_revoked`, `company.offboarding.personal_data_removed`) have the actor
  `system:offboarding`, whose `actor_kind` is `server`.

### Added: full company data export (#192)

Additive.

- `POST /v1/company/exports` (`requestCompanyExport`, `CompanyExport`) → 202: a company admin asks for a dated ZIP
  of CSV and JSON files of everything the company holds (profile, facilities, growing areas, growers, devices, lots,
  device events, cartons, shipments, lab reports and results, members without any secret, activity log), built by
  the background job. Needs a recent password confirmation (401 `reauthentication_required`); one export per company
  at a time (409 `export_in_progress`); at most 3 requests in any 24 hours (429 `too_many_exports`, `Retry-After`).
  Takes `Idempotency-Key`, so it joins the Go, Java and .NET SDKs' keyed POST lists. Audited
  `export.company.request`.
- `GET /v1/company/exports` (`listCompanyExports`, `CompanyExportList`): the company's 20 newest requests, their
  state (`queued`, `running`, `ready`, `failed`, `expired`), and for a ready one its size, SHA-256, file name and
  `expires_at`.
- `GET /v1/company/exports/{id}/download` (`downloadCompanyExport`) → `application/zip`, streamed, for 24 hours after
  the archive is ready (then 410 `export_expired`; 409 `export_not_ready` or `export_failed` before). Needs a recent
  password confirmation. Another company's export answers 404. An audited read, `export.company`.
- All three: tenant_admin and platform_admin acting for the company, through a signed-in session only (an API token,
  API client or the legacy token is refused, 403); the policy `company_export` is not an OAuth scope. The archive
  layout is documented in [company-export.md](company-export.md).

### Added: a company proposes its own facilities, CropPath approves them (#197)

Additive.

- `POST /v1/facility-proposals` (`proposeFacility`, `FacilityProposalCreate`): a company admin proposes a facility
  of the company it acts for: `code`, `name`, `address`, `province`, `district`, `lines`, never the slug or the GACC
  PHC code. It starts unapproved, with the default slug of its code (numbered when taken). Audited
  `facility.propose`. tenant_admin and platform_admin through a signed-in session only (an API token or API client
  is refused, 403); at most 20 proposals waiting per company (409 `too many pending proposals`).
- `GET /v1/facility-proposals` (`listFacilityProposals`, `FacilityProposalPage`): the platform's queue, every
  company's proposals waiting for approval, with the company's name and who proposed it when.
- `POST /v1/facility-proposals/{code}/approve {slug?, gacc_phc_code?}` (`approveFacilityProposal`): approve and set
  the slug and the PHC code in one change; audited `facility.proposal.approve`. `POST
  /v1/facility-proposals/{code}/reject {reason}` (`rejectFacilityProposal`, `FacilityProposalRejected`): the proposal
  is deleted so its code is free again; audited `facility.proposal.reject` with the reason. Both platform_admin only,
  across companies; the row goes to the proposing company's activity log.
- `Facility` gains `proposed_at` (null for a facility the platform created). Until CropPath approves a proposal,
  `POST /v1/lots`, `/v1/shipments`, `/v1/devices`, `/v1/gateways`, `/v1/harvest-keys` and
  `/v1/facilities/{code}/issuer-keys` naming it answer 409 `facility not approved`.
- The getting-started checklist's `facility` step links to `/admin/facilities#propose-facility`.

### Added: usage and limits of a company (#194)

Additive.

- `GET /v1/company/usage`: the selected company's usage (`CompanyUsage`: `tenant`, `warn_percent`, `limits`,
  `api_calls`). Each `CompanyUsageLimit` (`members`, `pending_links`, `devices`, `api_tokens`, `api_clients`,
  `webhooks`) has `used`, the enforced `limit` (null for devices: none is enforced), `warning` (from 80%) and
  `reached`. `api_calls`: the last 14 UTC days, newest first (`CompanyApiCallDay`: `day`, `calls`); a call is a
  request made with an API token or an API client's access token of the company. Counts only.
- tenant_admin, auditor and platform_admin (acting for the company) through a signed-in session only; API tokens, API
  clients and operators get 403. Not an OAuth scope.

### Added: contact CropPath support, the status page and platform announcements (#196)

Additive. Tag `support`; every route is session-only and not delegable to an API client.

- `GET /v1/help` (`getHelp`): any signed-in user; the platform announcements showing now (`LiveAnnouncement`) and
  CropPath's status page address (`status_page_url`, the deployment's `AGRITRACE_STATUS_PAGE_URL`; null hides the
  link). `Help`.
- `GET|POST /v1/support-requests`, `GET /v1/support-requests/{id}`: a company's staff (company admins, operators,
  auditors, and platform admins for the company) send CropPath a request (`SupportRequestCreate`: `subject`, `body`,
  optional `record_id`) and read their requests' status and reply (`SupportRequest`, `SupportRequestPage`). A company
  admin sees every request of the company, anyone else their own; another company's request is 404. Plain text, at most
  5 requests per person per hour, 10 per person per day and 30 per company per day (429 `too_many_support_requests`
  with `Retry-After`). Audited `support_request.create`.
- `GET /v1/platform/support-requests?status=&tenant=`, `PATCH /v1/platform/support-requests/{id}`
  (`SupportRequestUpdate`: `status`, `reply`): platform admins work the queue (`PlatformSupportRequest`). Audited
  `support_request.update`, in the request's company's activity log.
- `GET|POST /v1/platform/announcements`, `POST /v1/platform/announcements/{id}/expire`: platform admins post
  (`AnnouncementCreate`: `text`, `level`, `starts_at`, `ends_at`) and end the staff shell's banner notices
  (`Announcement`, `AnnouncementPage`); at most 20 live or scheduled. Audited `announcement.create` and
  `announcement.expire`.

### Added: a company admin unlocks a member's sign-in (#199)

Additive.

- `POST /v1/members/{user_id}/unlock` (`unlockMember`, `MemberUnlockResult`: `user_id`, `locked: false`,
  `was_locked`): clears the login lockout of the member's email. Wrong passwords and wrong two-step codes share one
  counter, so one unlock clears both. 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); a platform admin acting for the company may
  unlock any member of it; another company's member is 404. Needs a recent sign-in (SELF-1-2); session only (team
  management is never delegated). Audited `member.unlock` (`was_locked`; never the email or a failure count).
- `Member.locked` (every answer that carries a member): whether the member is locked out of signing in now. Never a
  failure count.

### Added: signed-in devices and sign out everywhere (#190)

Additive.

- `GET /v1/auth/sessions` (`listMySessions`): the signed-in user's live sessions in every company, each with the
  browser and system read from its user agent, when it was opened and last used (to the minute) and whether it is the
  one asking (`SignedInSession`). Never a token, its hash, an IP address or the raw user agent.
- `POST /v1/auth/sessions/{id}/revoke` (`revokeMySession`) ends one of the user's other sessions (400
  `current_session` for the one asking: sign out instead; another user's session is 404), and `POST
  /v1/auth/sessions/revoke-others` (`revokeMyOtherSessions`) ends all but the one asking. Session routes, audited
  `auth.session.revoke` and `auth.session.revoke_others`.
- `POST /v1/members/{user_id}/sessions/revoke {reason?}` (`revokeMemberSessions`): a company admin ends every session
  of a member who belongs to this company alone (409 `sign_out_by_support` for an account in another company too or
  with a platform admin or lab role); CropPath support acting for the company may, with a reason. Recent sign-in,
  session only (not delegable), audited `member.sessions.revoke`.

### Added: forgot password with a backup code (#191)

Additive.

- `POST /v1/auth/password/recover {email, backup_code, new_password}` (`recoverPassword`): for an account with
  two-step sign-in, one unused backup code sets a new password without a session. The code is used up, the password
  stored and every session of the account ended in one transaction; no session is opened (`PasswordRecovered`:
  `backup_codes_left`, `second_factor: "required"`), so the next sign-in asks for the new password and the second step.
  Audited `auth.password.recover` (never the code or a password).
- An unknown email, an account without two-step sign-in, a disabled account and a wrong, used or malformed code get
  the same 400 `email_or_backup_code_is_incorrect` after the same work, and count towards the email's login lockout.
  Anonymous like login: the login rate-limit bucket per client, plus 5 tries an hour per email named (429).

### Added: daily integrity anchors and inclusion proofs (#202)

Additive.

- `GET /v1/public/anchors` (`listPublicAnchors`): the daily anchors of the activity log, the evidence envelopes, the
  lot seals, the reviews and the envelopes held (not accepted) when the day was anchored, oldest first, `after` (a
  day) and `limit` (1 to 100, default 30). Each item gives the day's five Merkle roots, its counts, its day root, its
  anchor (chained to the previous day's) and its RFC 3161 timestamp (`pending`, or `verified` with genTime and the
  token). `IntegrityAnchorPage`, `IntegrityAnchor`, `IntegrityAnchorTimestamp`.
- `GET /v1/public/lots/{publicId}/anchor-proof[?event=]` (`getPublicLotAnchorProof`): the inclusion proof of a public
  lot's seal, or of one of its accepted events, in its day's anchor (`AnchorInclusionProof`; an event's record names
  no device: the SHA-256 of its stored body commits to it). A lot that is not public or not sealed, an event that is
  not one of its events, and a day not anchored yet answer the public lot's 404.
- Both are anonymous, side-effect-free and edge-cacheable (#177). The encoding is in
  `/developers/downloads/integrity-anchors.md`; `/developers/downloads/verify_anchors.py` checks the chain, the tokens
  (genTime at most 48 hours after the day) and the proofs with the Python standard library, and that a saved copy of the anchors is an unchanged prefix of the live chain.

### Changed: Device-recorded evidence needs a device CropPath approved (#201)

**BEHAVIOUR CHANGE**: the trust tier of device evidence now depends on CropPath's approval of the device. No
request is refused that was accepted before.

- Evidence counts as Device-recorded or above only when CropPath approved the device that sent it and the key that
  signed it, and, for a gateway's signature, that gateway. Evidence from a device, gateway or key that is not approved
  is accepted and stored as before and counts as Self-declared (reason `device_not_approved`). This applies to the
  measurement step, harvest records from the harvest app (#160), signed pack events (#136) and the shipping step's
  logger readings.
- A device or gateway a company registers (`POST /v1/devices`, `POST /v1/gateways`) is `pending` until a platform admin
  approves or rejects it; so is a key a company adds (`POST /v1/keys`), also on an approved device or gateway, until a
  platform admin approves it with its owner. Every device, gateway and key that existed when this change was deployed
  (migration 56) was approved then, so no lot's tier changed.
- Approving raises an open lot's provisional tier at its next recompute, never a sealed lot's. Rejecting (also an
  approved device or gateway, withdrawing its approval) lowers every lot whose evidence it sent, open or sealed.
- New platform admin routes: `GET /v1/device-approvals?approval=` (`listDeviceApprovals`, `DeviceApprovalPage`,
  `DeviceApprovalItem`; default `pending`, which also lists an approved device or gateway with a key waiting),
  `POST /v1/devices/{id}/approve` and `POST /v1/gateways/{id}/approve` (`DeviceApproval`: `keys`, the waiting keys the
  admin saw; exactly those are approved, 409 when one is no longer waiting), `POST /v1/devices/{id}/reject` and
  `POST /v1/gateways/{id}/reject` (`DeviceRejection`: `reason`, shown to the company; 409 when already rejected).
  Audited (`device.approve`, `device.reject`, `gateway.approve`, `gateway.reject`) in the company's activity log.
  Never an OAuth2 scope.
- `Device` and `Gateway` gain `approval` (`pending`, `approved`, `rejected`), `approval_reason` and `approval_at`;
  `Key` gains `approval` (`pending`, `approved`). The public lot and fruit journey steps gain `device_approval`
  (`PublicDeviceApproval`: `approved`, `approved_on`; null for a step no device signs).

### Added: getting-started checklist for a company (#189)

Additive.

- `GET /v1/company/onboarding`: the selected company's getting-started steps (`Onboarding`: `tenant`, `complete`,
  `hidden`, `hidden_at`, `steps`), in order, each `OnboardingStep` with `id`, `required`, `status` (`done`, `to_do`,
  `waiting_for_platform`), `count`, `total` and the console `link` where it is done. Computed from the company's own
  records at read time (counts only).
- `PUT /v1/company/onboarding {hidden}`: hide the checklist, or show it again; the only thing it stores. Audited
  `company.onboarding.update`.
- Both: tenant_admin and platform_admin (acting for the company) through a signed-in session only; API tokens, API
  clients, operators and auditors get 403. Not an OAuth scope.

### Added: two-step sign-in with an authenticator app (#187)

Additive. Clients that sign in to accounts without two-step sign-in see no change.

- `POST /v1/auth/login` and `POST /v1/auth/links/accept`: for an account with two-step sign-in, a correct password (or
  an accepted link) answers **202** `SecondFactorChallenge` (`{"second_factor": "required", "ticket", "expires_at"}`)
  with no session and no cookie. `POST /v1/auth/login/second-factor {ticket, code | backup_code}` then opens the
  session (200 `SecondFactorSession`: the `AuthSession` fields plus `second_factor` and `backup_codes_left`). The
  ticket lives 5 minutes, works once and takes at most 5 codes; wrong codes count towards the login lockout.
- New session routes for the signed-in user: `POST /v1/auth/two-factor/setup` (the secret and its `otpauth://` URI,
  once), `POST /v1/auth/two-factor/confirm {code}` (turns it on; 10 backup codes, once), `POST
  /v1/auth/two-factor/disable {password, code | backup_code, set_up_again?}` and `POST /v1/auth/backup-codes` (10 new
  codes, once). `POST /v1/auth/reauth` takes `code` or `backup_code`, required for an account with two-step sign-in.
  Turning it off ends the second-factor proof of every session of the account.
- `POST /v1/auth/password`: an account with two-step sign-in also sends `code` or `backup_code` (400
  `code_is_required` without one, 400 `current_password_or_code_is_incorrect` for a wrong one, which counts towards the
  lockout). For every account, the fresh session keeps the calling session's last password proof: a password change
  no longer counts as a recent sign-in for the routes that need one (`POST /v1/auth/reauth` does).
- `GET /v1/auth/me`, the login and link responses: new optional `two_factor` (`enabled`, `backup_codes_left`,
  `verified`, `required`, `deadline`). `GET /v1/members`: each member gains `two_factor`.
- New team routes: `GET`/`PUT /v1/company/security` (`require_two_factor`) and `POST
  /v1/members/{user_id}/two-factor/reset` (audited in this company's log and in the log of each other company the
  account belongs to).
- A signed-in session that must prove a second factor for the selected company and has not (a platform admin from this
  release; a company admin 60 days after it; a member of a company that requires it) gets **403 `two_factor_required`**
  on every route with bearer security until it sets up the app. API tokens and API clients are never asked.
- Migration 54: `user_two_factor`, `backup_codes`, `login_tickets`, `company_settings`, `two_factor_rollout` and
  `sessions.second_factor_at`.

### Correction: an audit row's `after.status` may be missing (#188)

Breaking on paper, accepted as a correction: the server never met the rule it removes.

- `AuditEntry.after` (`GET /v1/audit`) no longer requires `status`; `status` and `error` are both optional. The spec
  said every non-null `after` held the HTTP status, but the rows the server's command line (`cli:*` actors:
  `tenant.create`, `user.create`, `account_link.create` from create-invite, `api_token.create`, `api_token.revoke`,
  `auth.unlock`) writes never had one, and `GET /v1/audit` already served them. A client that requires `status`
  rejects such a page; treat a missing `status` as done (the change was made).
- From this release the command line records `status` too, the status the API answers for the same change (201 for a
  create, 200 for a revoke or an unlock). Rows written before keep none.

### Added: the company activity log's filters and CSV download (#188)

Additive.

- `GET /v1/audit`: new filters `entity_id` (one record), `action_prefix` (up to 30 comma-separated prefixes such as
  `lot.,carton.`), `since` and `until` (ISO 8601, +07:00 without an offset; until exclusive). A malformed filter is 400
  (`bad_action_prefix`, `bad_since`, `bad_until`, `bad_range`, `bad_entity_id`). The keyset cursor and the 200-row page
  are unchanged. Each item gains `actor_kind` (`member`, `support` for CropPath staff acting for the company,
  `api_token`, `api_client`, `server`, `other`) and `actor_name` (a member's display name, an API token's or API
  client's name, or null).
- `GET /v1/audit.csv`: the same rows and filters as CSV, at most 10,000 per file (`X-Next-Cursor` for the next file),
  for auditors and admins; an audited read (`export.audit`).
- New index `audit_log(tenant, at)` (migration 52).

### Added: the producer on export labels and the customs dossier (#186)

Additive.

- `GET /v1/lots/{lot}/export-label`: `fields.producer`, the lot's company as its company profile names it now (legal
  name, address, district, province, country; `CompanyProducer`), null until the company saves a profile. New problem
  `producer_missing` when the market's template requires the producer and the company has no profile.
- Export label templates: a `producer` field (captions and whether it is required). Every template returned has it; a
  `PUT /v1/export-label-templates/{market}` body may leave it out, and a version stored before this change reads with
  its built-in captions ("生产商" / "Producer"), not required. The console prints the legal name alone, on one line,
  on a carton label (a name too long for one line at 7 pt ends in an ellipsis), and the legal name with the address on
  a pallet label.
- `GET /v1/public/lots/{publicId}/customs-dossier` (and its print view): `producer`, the same object or null. It is not
  part of `sealed`: a profile edit changes `producer` and `digest`, never `sealed` or `seal`.

### Added: company profile (#186)

Additive.

- `GET /v1/company/profile`, `PUT /v1/company/profile`: the selected company's legal name, trading name, address,
  province, district or commune, country, tax or registration number, contact person, phone, email and website. Read
  by admins, auditors and operators; saved by company admins (a platform admin through `X-Tenant`). A PUT replaces the
  whole profile. Audited as `company.profile.update` with the names of the changed fields only.
- `GET /v1/company/logo`, `PUT /v1/company/logo?sha256=`: the company's logo, PNG or JPEG only, at most 256 KiB and
  1024 x 1024 pixels, checked by its magic bytes and its SHA-256. Audited as `company.logo.update`.
- Neither is available to API clients (OAuth2): company account management is not delegable.

### Added: company admins manage their team (#185)

Additive.

- `GET /v1/members` (`listMembers`, `MemberList`, `Member`): everyone who belongs to the selected company, by email,
  with their role here (and an operator's facilities), platform-managed roles read-only, whether the company turned
  them off, the account status, the last sign-in and when they joined; and the count of active admins.
- `PATCH /v1/members/{user_id}` (`updateMember`, `MemberUpdate`): one role per member (tenant_admin, operator or
  auditor), an operator optionally limited to facilities of the company. `POST /v1/members/{user_id}/disable` and
  `/enable` (`disableMember`, `enableMember`): turn the member's memberships in this company off or back on, the
  account and other companies unchanged. `POST /v1/members/{user_id}/password-link` (`createMemberPasswordLink`): a
  one-time link (24 hours), shown once, for a member who belongs to this company only (409 `reset_by_support`
  otherwise).
- `GET /v1/invitations`, `POST /v1/invitations`, `POST /v1/invitations/{id}/revoke` (`listInvitations`,
  `createInvitation`, `revokeInvitation`, `Invitation`, `InvitationCreate`): one-time invitation links (72 hours),
  shown once; 409 `already_a_member`; at most 200 active members and pending invitations, 50 pending links and 30 new
  links an hour per company.
- The last-admin rule: a change that would leave the company without an active admin is 409 `last_admin`. Changing a
  role to or from tenant_admin, turning a member off, turning an admin back on, inviting an admin and a password link
  need a recent password confirmation (401 `reauthentication_required`, #183). Audited (`member.update`,
  `member.disable`, `member.enable`, `account_link.create`, `account_link.revoke`).
- tenant_admin and platform_admin acting for the company, through a signed-in session only: an API token, API client
  or the legacy token is refused (403). `Tenant.members` and `Tenant.admins` no longer count a membership the company
  turned off.

### Added: one-time account links, first-admin invitations and admin recovery (#184)

Additive.

- `POST /v1/tenants/{id}/admin-invitations` (`createAdminInvitation`, `AdminInvitationCreate`, `AccountLinkCreated`):
  a platform admin creates a one-time link (72 hours) that lets the person with `email` join the company as
  tenant_admin. With an active company admin in place it is the platform's admin recovery and needs a `reason`.
- `POST /v1/tenants/{id}/admins/{user_id}/recovery-link` (`createAdminRecoveryLink`, `RecoveryLinkCreate`): a one-time
  link (24 hours) that lets a company admin choose a new password; accepting it ends every session of the account. A
  `reason` is required. `GET /v1/tenants/{id}/admins` (`listTenantAdmins`, `TenantAdminList`): the company's admins
  that recovery can reset.
- These three: platform_admin through a signed-in session only, the two POSTs with a recent password confirmation
  (#183). A link is returned once (`no-store`) and only the SHA-256 of its token is stored, so these POSTs refuse an
  `Idempotency-Key` (400). At most 50 pending links and 30 new links an hour per company (409). Audited
  (`account_link.create`, in the company's own log; never the link).
- `POST /v1/auth/links/inspect` and `POST /v1/auth/links/accept` (`inspectAccountLink`, `acceptAccountLink`,
  `AccountLinkToken`, `AccountLinkInfo`, `AccountLinkAccept`): anonymous, rate limited like login. Inspect tells the
  company, role, email and expiry; accept creates the account (or, for an email with an account, checks its password)
  and opens a session like login. Every unusable token is the same 404 `link_not_valid`.
- `Tenant` (`GET /v1/tenants`, `POST /v1/tenants`) gains `members` and `admins`, the counts of active members and
  active company admins.

### Added: re-enter the password for sensitive actions (#183)

Additive for API tokens and API clients: they are never asked. A signed-in session may get a new 401.

- `POST /v1/auth/reauth` (`reauthenticate`, `ReauthRequest`): the signed-in user confirms their password (204); a
  wrong one counts towards the login lockout. Audited `auth.reauth`.
- Operations that create credentials or change who may act for the company refuse a session whose last password
  proof is more than 10 minutes old: 401 `reauthentication_required`, and nothing is done. Confirm with
  `POST /v1/auth/reauth`, then repeat the request. From this release `POST /v1/api-tokens`, `POST /v1/oauth-clients`
  and `POST /v1/webhooks/{id}/rotate-secret` (a session only: an API token or API client rotating a webhook secret is
  not asked); later operations say so in their description and their 401.

### Added: harvest app key registrations (#160)

Additive.

- `POST /v1/harvest-keys` (`registerHarvestKey`, `HarvestKeyRegister`, `HarvestKey`): the harvest app (`/harvest`)
  sends the public half of the ECDSA P-256 key it generated for a collection point (a facility). The registration is
  `pending` until a company admin decides; the same key again for the same facility answers the stored registration
  with 200. 409 when the key is registered by another company or for another facility. Audited
  `harvest_key.register` (never the PEM).
- `GET /v1/harvest-keys` and `GET /v1/harvest-keys/{kid}` (`listHarvestKeys`, `getHarvestKey`, `HarvestKeyPage`): the
  registrations, an operator only those of its facilities.
- `POST /v1/harvest-keys/{kid}/approve` and `/reject` (`approveHarvestKey`, `rejectHarvestKey`): final. Approval
  creates the install's device (profile `vn.agritrace.harvest-app`) and its key in the same transaction, and ingest
  accepts its signed harvest messages from then on; since #201 that device and key also wait for CropPath's approval
  before its evidence counts as Device-recorded. Audited `harvest_key.approve` and `harvest_key.reject`.
- Registering and reading are not delegable to an API client; deciding one takes the `device_admin` scope (#171).

### Changed: caching headers of the public reads (#177)

Additive: only `Cache-Control` and two public response fields change.

- The anonymous lot, fruit, resolve, credential, EPCIS, customs dossier and DID document reads answer
  `Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=300` (was `public, s-maxage=60`): the edge
  may keep a record 60 seconds and serve it up to 300 seconds stale while it refetches; browsers always revalidate. A
  404 answers `public, max-age=0, s-maxage=60`. A public answer without its own header (an error) is `no-store`, and
  every other API answer (staff, devices, sign-in) is `private, no-store`.
- `GET /v1/public/fruits/{publicId}` logs a scan only for the web server's own render, which now reads the page with
  `X-Agritrace-No-Scan: 1` (cacheable, logs nothing) and logs the scan in a separate uncached read. A read that logged
  a scan is `private, no-store`. Both headers are internal: other clients get `scan: null` as before.
- `ReportReceipt` (`POST /v1/public/reports`) gains `fruit` and `lot` (`PublicCurrentStatus`: `status`,
  `status_since`, `status_reason`, `tier`), the current status of the reported fruit and its lot read when the report
  was filed, so a page can show it although an edge-cached record may still be older.

### Added: pack events signed by the packing station (#136)

Additive.

- `POST /v1/ingest/...` takes a `pack` event (profile `vn.agritrace.pack-station`, one `pack.carton` reading per
  carton, the seal number in `context.seal`) and compares it with the lot's packing records: the lot, its facility and
  the device's, the seal number 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.
- `POST /v1/lots/{lot}/seal`: the packing step is Device-recorded only when the facility's packing station signed pack
  events before the seal that cover every carton with its current fruits and net mass and this seal number, from a key
  never revoked for compromise; otherwise it stays Self-declared, as before. A pack event whose seal number differs
  from the pack seal raises `pack_mismatch` and holds the lot; the seal is still recorded.

### Added: consignee and document references on a shipment (#153)

Additive, with one **BEHAVIOUR CHANGE**: a shipment to a market with required papers no longer departs without them.

- **BEHAVIOUR CHANGE**: `POST /v1/shipments/{code}/depart` answers 409 `missing_paperwork`, naming the missing items,
  when the shipment lacks its destination market's required papers; nothing departs. For `CN`: the consignee, a
  phytosanitary certificate and a test report. A client that departed such shipments without them must first record
  them with the two operations below.
- `PUT /v1/shipments/{code}/consignee` (`setShipmentConsignee`, `ShipmentConsigneeSet`): legal name, address, ISO 3166-1
  alpha-2 country, optional GLN and importer registration. `PUT /v1/shipments/{code}/documents`
  (`setShipmentDocuments`, `ShipmentDocumentsSet`): document references (type from a fixed list, number, issue date,
  optional SHA-256 of an uploaded PDF). Edited freely while the shipment is open; after the departure a `reason` is
  required and the change is kept as an amendment (at most 50 amendments per shipment; one more is 409). Audited
  (`shipment.consignee.set`, `shipment.documents.set`; never a name or an address).
- `Shipment` gains `consignee`, `documents`, `paperwork` (what the market requires and what is missing) and
  `amendments`.
- `GET /v1/lots/{lot}/epcis` adds the departure of the lot's shipment as a shipping ObjectEvent whose
  `bizTransactionList` lists the document references; documents amended after the departure give it a new `eventID`.
  The records export (#152) fills the consignee columns.

### Added: export labels for China cartons and pallets (#151)

Additive.

- `GET /v1/lots/{lot}/export-label?market=` (`getLotExportLabel`, `ExportLabel`): what the market's label prints
  (fruit, origin, export country, orchard and packing house with their registration codes only when cross-checked
  against the published lists of #150, packing date), a page of the selected cartons with net mass, count and QR URL,
  the pallet totals, the template in force, and the `problems` that keep it from being an export label (`ready`).
- `POST /v1/lots/{lot}/export-label/prints` (`recordExportLabelPrint`, `ExportLabelPrintCreate`, `ExportLabelPrint`):
  records that carton or pallet labels were printed, with the `template_version` and carton count the console read.
  409 `label_not_ready` (naming the problems) when the label is not ready for export, and 409 `label_changed` when the
  template in force or the selection's carton count differs from what was sent; nothing is logged then. Takes
  `Idempotency-Key`. Audited `export_label.print`.
- `GET /v1/export-label-templates` and `PUT /v1/export-label-templates/{market}` (`listExportLabelTemplates`,
  `putExportLabelTemplate`, `ExportLabelTemplate`): platform admins read and edit each market's template (text only);
  every save is a new version, version 0 is the built-in one, `CN` is the only market. Audited
  `export_label_template.put`.

### Added: OAuth2 client credentials for company integrations (#171)

Additive.

- `POST /v1/oauth/token`: RFC 6749 §4.4 client credentials grant. The client authenticates with HTTP Basic or with
  `client_id` and `client_secret` in the form body and gets a bearer access token (`ago_...`) valid for 900 seconds,
  with the client's scopes or the subset asked for in `scope`. Errors are RFC 6749 §5.2 bodies (`error`,
  `error_description`), with the API's `code` beside them. Rate limited per client address; a client holds at most 20
  live tokens.
- `POST /v1/oauth/revoke`: RFC 7009 revocation of one of the client's own access tokens.
- `GET /v1/oauth-clients`, `POST /v1/oauth-clients`, `POST /v1/oauth-clients/{id}/revoke`: a tenant's admins, through
  a signed-in session, list, register (the secret is returned once) and revoke API clients. A client has a role
  (tenant_admin, operator or auditor), scopes (the names of the API's permissions, for example `lot_read`,
  `lot_write`, `tenant_read`) and, for an operator client, an optional list of facilities. Revoking a client ends
  every token it holds at once.
- `Authorization: Bearer` now also accepts these access tokens; a request outside the token's scopes is 403
  `role not permitted`. API tokens (`agt_...`) and legacy tokens are unchanged.
- A lot seal made by an API client names it `client-<id>` as its operator, and so does an EPCIS capture's
  `captured_by`.
- Scopes are listed in the OpenAPI `oauth2` security scheme, and each operation an API client may call names its scope
  in its `security`. `epcis_capture` (`POST /v1/epcis/capture`) and `records_export` (the four records-export
  downloads) are dedicated scopes that no other scope implies; `webhook_admin` opens the webhook routes (#168).

### Added: versioning policy and deprecation headers (#171)

Additive.

- [versioning.md](versioning.md): the v1 stability rules, the client obligations and the deprecation process with a
  minimum notice of 180 days.
- A deprecated route answers with `Deprecation` (RFC 9745), `Sunset` (RFC 8594) and `Link` headers. No route is
  deprecated.
- Every change to the OpenAPI document is checked for breaking changes against the last pushed version before it is
  pushed.

### Added: outbound webhooks (#168)

Additive.

- `POST /v1/webhooks` (`createWebhook`, `WebhookSubscriptionCreate`, `WebhookSecret`), `GET /v1/webhooks`
  (`listWebhooks`, `WebhookSubscriptionList`), `GET /v1/webhooks/{id}` (`getWebhook`, `WebhookSubscription`),
  `PATCH /v1/webhooks/{id}` (`updateWebhook`, `WebhookSubscriptionUpdate`) and
  `POST /v1/webhooks/{id}/rotate-secret` (`rotateWebhookSecret`): a company registers HTTPS endpoints for event types,
  at most 20 per company. The URL must be https, without credentials or fragment, and every address its host resolves
  to must be public. The signing secret (`whsec_...`) is shown once, on create and on rotate. `enabled: false`
  disables a subscription and fails its pending deliveries (`subscription_disabled`). Audited (`webhook.create`,
  `webhook.update`, `webhook.rotate_secret`; never the secret).
- `GET /v1/webhooks/{id}/deliveries` (`listWebhookDeliveries`, `WebhookDeliveryPage`, `WebhookDelivery`) and
  `POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` (`redeliverWebhook`): the delivery log, newest first
  (deliveries are removed 30 days after they were queued), and sending a delivery again with the same event id and
  body. Audited `webhook.redeliver`.
- Event types, each described under the document's top-level `webhooks`: `lot.sealed`, `lot.recalled`,
  `lot.withdrawn`, `lab_result.recorded`, `shipment.departed`, `lot.trust_tier_changed` and `report.filed`.
- Every delivery is a POST of JSON with the Standard Webhooks headers `webhook-id`, `webhook-timestamp` and
  `webhook-signature` (HMAC-SHA256); see [webhooks.md](webhooks.md). Answer 2xx within 10 seconds; a failed delivery
  is retried with exponential backoff for 12 attempts (about 21 hours), and 50 failed attempts in a row disable the
  subscription.
- tenant_admin and platform_admin acting for the company, through a session or an API token of their role (an API
  client needs the `webhook_admin` scope from #171).

### Added: a lab's approvals for destination markets (#154)

Additive.

- `GET /v1/labs/{code}/approvals`, `POST /v1/labs/{code}/approvals`, `PATCH /v1/labs/{code}/approvals/{id}`
  (`listLabApprovals`, `createLabApproval`, `updateLabApproval`, `LabApproval`, `LabApprovalCreate`,
  `LabApprovalUpdate`, `LabApprovalList`): platform admins record a lab's approval for a destination market (approving
  body, reference, analytes covered, validity, optional source URL and evidence SHA-256), change it or withdraw it
  (`status` `withdrawn`; nothing is deleted); a lab user reads its own lab's. At most 100 per lab. Audited
  (`lab_approval.create`, `lab_approval.update`).
- A lab result counts toward Lab-verified for a market only when an approval valid on the report's signed date lists
  the analyte; otherwise the lab step is at most Cross-checked (reason `lab_not_approved_for_market`). Each change
  queues every lot the lab reported on for a trust recompute.
- `PublicLot.lab` and `PublicCustomsDossier.lab_report` gain `market_approval` (`PublicLabMarketApproval`: `market`,
  `approved`, `reference`).

### Added: the authorities' published code lists and the registration cross-check (#150)

Additive. Platform admin routes; before a list is imported nothing changes.

- `PUT /v1/registry-sources/{sha256}` (`uploadRegistrySource`): the file the authority published (PDF, XLSX, XLS or
  CSV, at most 1 MiB) under its SHA-256, which the server checks (422 on a mismatch).
- `POST /v1/registry-lists` (`importRegistryList`, `RegistryListImport`): a PUC (growing areas) or PHC (packing houses)
  code list for a market and crop, converted to CSV and citing the original's `source_sha256`; it supersedes the
  current list of the same kind, market and crop. `POST /v1/registry-lists/{id}/retire` (`RegistryListRetire`) takes a
  current list out with a reason. `GET /v1/registry-lists`, `GET /v1/registry-lists/{id}`, `.../entries`, `.../file`
  and `.../source` read them. Audited (`registry_list.import`, `registry_list.retire`, `registry_source.upload`).
- `GET /v1/registry-matches?kind=` (`listRegistryMatches`, `RegistryMatchPage`): every company's PUC or PHC codes with
  their check: `matched`, `suspended`, `revoked`, `expired`, `mismatch`, `not_found`, `no_list` or `no_code`, and
  `stale` when the list is older than its maximum age (30 days by default).
- The registration step of a lot is Cross-checked only when the growing area's and the facility's codes are both
  matched on lists that are not stale and the area's crop is the lot's product. The pack seal freezes the check into
  the lot's sealed record, which the customs dossier's `registry_entry` reads.

### Added: request and database metrics (#129)

Additive.

- `GET /v1/metrics` (`getMetrics`): this process's metrics in the Prometheus text format (version 0.0.4): request
  latency histograms per route, SQL statements per request, time spent waiting for the database, and public scans
  logged. Label values are bounded (no ids, addresses or tokens). platform_admin only; not audited; `no-store`.

### Added: Idempotency-Key on POST requests (#169)

Additive: the header is optional.

- The POST operations of the company's records, devices and settings take an optional `Idempotency-Key` header (1
  to 255 visible ASCII characters), scoped to the company and the caller; each lists it. The first request runs; a
  2xx answer (status, body and headers) is stored and replayed for 24 hours to every request with the same key,
  method, path, query and body, 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 runs, 409
  `idempotency_key_in_use` with `Retry-After`. A request that fails before its change commits releases the key. A
  change that committed is never run again, even when its answer could not be stored: 409 `idempotency_key_in_use`
  for up to 5 minutes, then `idempotency_key_used`. A malformed or repeated header is 400
  `invalid_idempotency_key`.
- An operation whose answer shows a secret or a link once refuses the header (400): `POST /v1/api-tokens`,
  `POST /v1/webhooks`, `POST /v1/webhooks/{id}/rotate-secret`, `POST /v1/oauth-clients`, `POST /v1/invitations`,
  `POST /v1/members/{user_id}/password-link`, `POST /v1/tenants/{id}/admin-invitations`,
  `POST /v1/tenants/{id}/admins/{user_id}/recovery-link`, and the OAuth2 `POST /v1/oauth/token` and
  `POST /v1/oauth/revoke`. Each keyed operation lists the header and its 409 and 422 answers.

### Added: records-request export (#152)

Additive.

- `GET /v1/lots/{lot}/records-export.csv` and `GET /v1/lots/{lot}/records-export.json` (`getLotRecordsExportCsv`,
  `getLotRecordsExportJson`, `RecordsExport`, `RecordsExportRow`): the records of one lot for an authority or a buyer:
  the critical tracking events, the registry facts frozen at seal, every lab result, the recall if 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 (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`.
- `GET /v1/records-export.csv` and `GET /v1/records-export.json` (`getRecordsExportCsv`, `getRecordsExportJson`): the
  same rows for the company's lots created in `[start, end)` (ISO 8601; +07:00 without an offset; at most 366 days),
  at most 50 lots per page, the next page by `next_cursor` (JSON) or `X-Next-Cursor` (CSV).
- Audited reads (`export.records`), downloaded as attachments, never cached. A CSV text cell starting with `=`, `+`,
  `-`, `@`, a tab or a carriage return gets a leading `'`. tenant_admin, platform_admin and auditor; an OAuth2 client
  needs the dedicated `records_export` scope (#171).

### Added: batch operations for ERP integrations (#170)

Additive.

- `POST /v1/sessions/{id}/fruits/batch` (`allocateFruitBatch`), `POST /v1/lots/{lot}/cartons/batch`
  (`createCartonBatch`), `POST /v1/lots/{lot}/carton-contents/batch` (`setCartonContentsBatch`),
  `POST /v1/harvests/batch` (`declareHarvestBatch`) and `POST /v1/growers/batch` (`createGrowerBatch`): the batch form
  of the single operation, allowed like it and audited once per batch.
- A batch commits whole or not at all. Every item is validated first and every invalid item is listed (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 that item's status and index). At most 1,000 items and a
  body of 1 MiB.
- Rate limited per company and caller: bursts of 10 batches, then one every 6 seconds (429 with `Retry-After`).
- They take `Idempotency-Key` (#169); a batch key used more than 24 hours earlier answers 409 for the same request and
  422 `idempotency_key_reused_with_a_different_request` for another one.

### Added: EPCIS 2.0 capture from partner systems (#167)

Additive.

- `POST /v1/epcis/capture` (`captureEpcis`, `EpcisCaptureReport`): one GS1 EPCIS 2.0 JSON-LD `EPCISDocument`
  (`schemaVersion` 2.x, at most 500 events, a body of at most 1 MiB; otherwise refused as a whole with 400 or 413 and
  nothing written). The report has one line per event, in document order: `accepted` (stored), `duplicate` (the
  company already holds this `eventID` with the same content, so a retry is safe) or `rejected` with a code such as
  `invalid_event`, `unsupported_event_type`, `unsupported_biz_step`, `event_id_conflict` or `unknown_reference`.
  ObjectEvent, AggregationEvent and TransformationEvent for commissioning, harvest, receiving, packing and shipping,
  naming lots, cartons or shipments of the company. A captured event is the partner's statement and counts as
  Self-declared. tenant_admin and platform_admin; an OAuth2 client needs the dedicated `epcis_capture`
  scope (#171). Takes `Idempotency-Key` (#169).
- `GET /v1/lots/{lot}/captured-events` (`listLotCapturedEvents`, `CapturedEventPage`, `CapturedEvent`): the events
  captured for the lot (naming the lot, one of its cartons or its shipment), oldest first, one page at a time.

### Added: a report's scan history and the category filter (#74)

Additive.

- `GET /v1/reports/{id}` (`getReport`, `ReportDetail`): one report as the list shows it, with the contact (null once
  erased) and the reported fruit's newest 50 scans, newest first: number, time, country, region, city and device
  class, never an address or its hash. tenant_admin and platform_admin acting for the company; another company's
  report is 404. Not audited, `no-store`.
- `GET /v1/reports`: new filter `category` (one report category; 400 for anything else).

### Added: the commands a device accepts (#70)

Additive.

- `Device` (`GET /v1/devices`, `GET /v1/devices/{id}`, `POST /v1/devices`, `PATCH /v1/devices/{id}`) gains `commands`:
  the downlink commands the device's profile declares, sorted by name, the only names
  `POST /v1/devices/{id}/commands` accepts for that device (an operator limited to facilities may issue `calibrate`
  only).

## v1 baseline (2026-10-09)

The API as its OpenAPI document described it on 2026-10-09. This changelog starts here.
