Skip to main content

Types & schemas

Zod schemas in packages/core/src/schemas.ts are the single source of truth for this codebase: every request body/query is validated at runtime against one of these, and every TypeScript type is derived from the schema with z.infer rather than hand-written as a separate interface. This page mirrors those schemas — if this page and the code ever disagree, the code is correct; file an update against this repo.

Request types​

Request schemas are plain z.objects, so unknown keys are stripped silently (Zod's default), not rejected. The exception is CreatePlantInput and its nested objects: they are strict, and an unknown key is a 422. The project uses Zod 3.25, and the example validation messages on the API pages are Zod 3's defaults.

CreatePlantInput​

Body of POST /v1/plants: the create-plant wizard (screens 08-11) sent as one request. Strict: unknown keys are rejected. On every optional field, null or a blank/whitespace string means "not sent", and nothing is stored for it. null on a required field is still a 422.

{
// Step 1 — Plant Details
name: string; // trimmed, 1-120 chars, required
plantType: PlantType; // required
countryCode: string; // ISO 3166-1 alpha-2, one of the 249 assigned codes, case-insensitive, stored upper-cased, required
address?: PlantAddressInput | null;
timezone?: string | null; // IANA zone name or "UTC" only (offsets/abbreviations rejected), canonicalised; required unless countryCode is "PK" (then defaults to "Asia/Karachi")
// Step 2 — Solar System
solarMode: SolarMode; // required
pvCapacityKwp?: number | null; // > 0, max 100,000; required unless solarMode is NONE, forbidden when NONE
// Step 3 — Grid Connection
gridConnection: GridConnection; // required; OFF_GRID forbids exporting solar modes
electricityRate?: ElectricityRate | null;
// Retired 2026-11-20 — accepted with ANY value and ignored (never a 422, never stored or sent):
// batteries, hasBattery, batteryCapacityKwh, batteryPowerKw, batteryBrand, batteryBrandOther
}

Plant create takes no battery data (owner decision 2026-11-20, ADR 0029; the 2026-11-19 CreateBatteryItem / BatteryBrand are gone). Batteries are stored per device on the TCP server (batteries) and added there with add_device_battery after the inverter is registered. UpdatePlantInput ignores the same fields (below).

UpdatePlantInput​

Body of PATCH /v1/plants/{plantId}: the mobile Plant Settings screen. Strict, and at least one field must be present. Every field is optional with the same per-field rule as CreatePlantInput. null or blank means "not sent" and never clears a value. address and electricityRate are replaced whole.

{
name?: string | null;
plantType?: PlantType | null;
countryCode?: string | null; // to a non-PK country requires timezone; to PK defaults it to "Asia/Karachi"
address?: PlantAddressInput | null;
timezone?: string | null;
solarMode?: SolarMode | null; // NONE also removes the stored pvCapacityKwp
pvCapacityKwp?: number | null;
gridConnection?: GridConnection | null;
electricityRate?: ElectricityRate | null;
// Retired 2026-11-18: the five battery fields are accepted and ignored. A body with
// only them is a valid no-op (200), and every edit removes their stored copies.
}

CreatePlantInput's cross-field rules (capacity vs solarMode, OFF_GRID vs exporting modes) are checked against the plant after the change is merged onto the stored one. On a pre-2026-09-24 plant, a rule whose fields are missing is skipped, and the stored capacityKw counts as pvCapacityKwp.

Plant enums​

type PlantType = 'RESIDENTIAL' | 'COMMERCIAL' | 'INDUSTRIAL';
type SolarMode = 'NONE' | 'SELF_CONSUMPTION' | 'GRID_EXPORT' | 'SELF_CONSUMPTION_GRID_EXPORT';
type GridConnection = 'GRID_CONNECTED' | 'OFF_GRID';

Exactly three plant types (owner decision Q1, 2026-10-27) on every surface: mobile and web create/patch bodies, the web list plantType filter, geo/summary, the public share projection and plan scope rules. Any other value in a body is 422 VALIDATION_FAILED; in a query parameter, 400 VALIDATION_FAILED. The earlier UTILITY/OTHER values were removed. Stored legacy values are read tolerantly: a plant still carrying a retired UTILITY or OTHER is returned as INDUSTRIAL or COMMERCIAL respectively (readPlantType in packages/core/src/schemas.ts), so no response carries a value outside the three. Stored plant-type references are mapped the same way on read — maintenance-plan scopeRule.plantTypes, notification-rule PLANT_TYPE targets and saved-view plantType filters — while inputs stay strict. The owner rewrites stored values with npm run migrate:plant-types (see Operations).

GRID_EXPORT and SELF_CONSUMPTION_GRID_EXPORT are the exporting modes (EXPORTING_SOLAR_MODES in code). They're rejected for an OFF_GRID plant.

PlantAddress​

Input (PlantAddressInput): strict, and every part optional ("missing parts are simply left out"). null or a blank part is dropped. If no parts are left, the whole address is treated as not sent, so {} stores nothing.

{
formatted?: string | null; // trimmed, max 400 chars, e.g. "Karachi, Sindh, Pakistan"
city?: string | null; // trimmed, max 120 chars
region?: string | null; // trimmed, max 120 chars (province/state)
latitude?: number | null; // -90..90 } both or neither —
longitude?: number | null; // -180..180 } from "Use current location" / "Pick on map"
}

Stored/returned (PlantAddress): the same keys, with only the non-blank parts present, and never null.

ElectricityRate​

Strict. Both keys required if the object is sent.

{
amountPerKwh: number; // >= 0, max 100,000 — price of one unit (1 kWh)
currency: string; // 3 letters (ISO 4217 shape, not checked against the list), stored upper-cased, e.g. "PKR"
}

ClaimDeviceInput (D02 body)​

The POST /v1/plants/{plantId}/devices body. Lenient: unknown fields are dropped. ADR 0012: the call only binds the serial to the plant.

{
serial: string; // trimmed, 3-64 chars, ^[A-Za-z0-9._ -]+$ (spaces allowed), required
model?: string; // trimmed, max 80 chars; null or "" = unset; stored on the binding as free text
label?: string; // trimmed, max 120 chars; null or "" = unset
type?: 'INVERTER' | 'LOGGER' | 'METER' | 'BATTERY' | 'OTHER'; // accepted and ignored (ADR 0012)
}

Uniqueness uses the normalised serial (NFKC, upper-cased; spaces and dashes removed, . and _ kept), so SN-1 A, sn1a and SN1A are the same device. The normalised serial must be 3–64 characters of [A-Z0-9._]. The response keeps the serial as typed.

ListQuery​

Shared by every list endpoint today (GET /v1/plants, GET /v1/plants/{plantId}/devices).

{
limit: number; // coerced from string, integer, 1-50, default 25
cursor?: string; // opaque, from a previous response's nextCursor
}

limit is server-capped at 50. A value over 50 (or under 1, or non-numeric) is rejected with 422, not clamped, so there's no way to ask this API for an unbounded page. cursor is opaque and never a page number — see CursorV2 below for what it actually contains now, and never construct one by hand.

Now parsed by defineListQuery (FR-020, packages/core/src/pagination/list-query.ts), replacing the plain z.object shape above as of this writing: both list-plants.ts and list-devices.ts build their query with defineListQuery({}) (no declared filters/sort yet) and parse it { strict: false }. It reads event.rawQueryString with URLSearchParams instead of queryStringParameters, because API Gateway payload 2.0 joins repeated params with commas (status=A&status=B → "A,B"), which would otherwise corrupt a value like q that legitimately contains one. It supports declared, typed, repeatable filters (OR'd), a declared sort allow-list, and a q search term (2-64 chars) — none of which either route declares today, so in practice both still only accept limit/cursor. On a strict route (none live yet) an unknown param is 400 VALIDATION_FAILED with details.unknown; a bad sort/limit/q/filter value is 422 VALIDATION_FAILED (details.allowed for a bad sort). On the lenient routes above (CR-13) an unknown param is ignored and a bad sort/limit/q/ filter value falls back to its default (or is dropped) instead of erroring. The returned shape adds filters: Record<string, string[]> and sort?: string alongside limit/cursor — unused by either current route, but part of the contract a future filtered/sorted list route builds on.

SetSelectedPlantInput​

{
plantId: string; // trimmed, min 1 char, required
}

Schemas defined, not yet used by any route​

These exist in packages/core/src/schemas.ts today but no handler or route references them yet — they're the contract a later feature will build against. Treat them as unstable until a route actually uses them.

ErrorEnvelope​

The error envelope above, as a Zod schema (error.code is ErrorCodeSchema, an enum derived from ERROR_STATUS so the two can never drift). Not imported by http/respond.ts yet — that file builds the same shape by hand.

CursorV2 (pagination v2, FR-018)​

Live on both of today's list routes (GET /v1/plants, GET /v1/plants/{plantId}/devices, packages/core/src/pagination/cursor.ts), even though the ListQuery.cursor field's own declared type is still just string — the v2 structure is internal to this opaque value, not part of the request schema.

{
v: 2;
h: string; // 16 hex chars — a query-binding hash, not a security control
k?: Record<string, unknown>; // the DynamoDB ExclusiveStartKey (single-source queries)
m?: Array<{ // k-way-merge per-source positions (FR-019), at most 10 — see below
s: string; // source id
k: Record<string, unknown> | null;
done?: true;
}>;
}

h is the first 16 hex chars of SHA-256(routeKey | orgContext | normalised filters | sort) — binding the cursor to the exact query that produced it. Decoding checks, in order: length ≤ 2,048 chars, valid base64url/JSON, v === 2 (which also rejects every pre-cursor-v2 value — a bare ExclusiveStartKey with no v field at all), h matches the query about to run, and the key's partition attribute matches the partition the next query is about to hit (so a cursor minted for one user/plant/collection can't be replayed against another's). Both current routes stay lenient (CR-13): any of those checks failing silently restarts the caller from page one, rather than 400 INVALID_CURSOR — see API overview → Pagination. A strict route (none live yet) would throw INVALID_CURSOR on the same checks instead.

A planned k-way merge cursor extension (multiple ordered sources merged into one page, FR-019, packages/core/src/pagination/merge.ts) is authored but not yet wired into any route's cursor — no route lists over more than one source today, so k above is always a single ExclusiveStartKey, never a per-source array.

IntegrationEnvelope (TCP/alert event contract, FR-028)​

Live, unlike the rest of this page's "not yet used" group above: packages/core/src/integration/consume.ts's consume() validates every inbound from-tcp/alert-events message against IntegrationEnvelope.safeParse before dispatching it — a parse failure is exactly what maps to the invalid result (batch item failure, retried then DLQ). See Architecture → Inbound: TCP → SQS → consume for the full flow; that whole pipeline is authored but not deployed (IntegrationStack — and everything it invokes — needs -c busEnabled=true; renamed from withIntegration, T002-148, CR-26 — a single flag now both creates the stack and enables it, see Infrastructure → IntegrationStack).

.passthrough(), so a handler never 422s on a field a newer writer added.

{
specversion: '1.0';
id: string; // ULID
type: string; // e.g. "plant.created.v1"
source: string;
time: string; // ISO-8601 datetime
subject?: string; // "<aggregateType>/<id>", e.g. "plant/<id>", when present
correlationId?: string; // max 64 chars
causationId?: string; // ULID
seq: number; // integer, >= 1
data: Record<string, unknown>;
}

Also the shape packages/core/src/outbox.ts's Envelope/buildEnvelope builds for the OUTBOUND side — the two now agree on every field except correlationId, which IntegrationEnvelope treats as optional while outbox.ts's Envelope always sets it (the originating request's correlation id). buildEnvelope itself isn't called by any handler yet (002 ships the stream→outbox→SNS pipeline, not a feature that publishes through it), so that half of the contract is exercised by tests, not live traffic.

IdempotencyKeyHeader / IfMatchHeader​

Header-value shapes for a planned Idempotency-Key (^[A-Za-z0-9_-]{1,128}$) and If-Match (^(W\/)?"\d{1,10}"$ — a quoted integer version, optionally weak). No current route declares idempotency: 'required' | 'optional' or versioned: true in lib/routes.ts, so neither header is read or validated by any handler today.

LookupQuery / LookupResult​

Live as of T002-103/104 — see Search, lookup & catalog → GET /v1/lookup for the full request/response/error contract.

// query
{ code: string } // trimmed, max 80 chars; a display code ("PL-0518"), a device id (ULID) or a device serial — /^(?:[A-Z]{1,4}(-\d{4})?-\d{2,}|[A-Z0-9._][A-Z0-9._ -]{2,})$/i; upper-cased server-side

// response
{ type: string; id: string /* ULID */; code: string; orgId: string }

SuggestionsQuery / SuggestionItem​

Live as of T002-107/108/109 — see Search, lookup & catalog → GET /v1/search/suggestions for the full request/response/error contract.

// query
{ q: string; types?: string[]; limit: number /* 1-20, default 6 */ }

// one hit
{ type: string; id: string /* ULID */; label: string; sublabel?: string; matchedField: string; code?: string }

CatalogResponse​

Live as of T002-112/113/114 — see Search, lookup & catalog → GET /v1/catalog/{name} for the full request/response/error contract.

{
name: string;
version: string;
items: Array<{ value: string; label: string; deprecated?: boolean }>;
}

Response types / DTOs​

Every one of the seven legacy routes below now builds its response through an explicit allow-list Zod projection (packages/core/src/projections/legacy.ts — toLegacyMeView, toLegacyPlantView, toLegacyPlantListEnvelope, toLegacyDeviceView, toLegacyDeviceListEnvelope), applied at the handler boundary on the repository's return value, immediately before the response is sent. This replaces an earlier approach that destructured out only the DynamoDB-only attributes it knew about by name (PK, SK, GSI1PK, GSI1SK, entityType) — which would have started leaking a new internal attribute (GSI2*/GSI3*, version, schemaVersion, operatorOrgId, copyVersion, see Database entity shapes below) the moment a later feature added one to a shared item shape. The allow-list schemas below name every field that's returned; anything not named here is silently dropped, never returned, even if present on the underlying item. The documented field sets below are unchanged by this — it's a leak-proofing change, not a shape change.

plantType is always one of the three values above, including on legacy mobile reads: a stored retired UTILITY/OTHER is mapped to INDUSTRIAL/COMMERCIAL on read (readPlantType).

UserProfile​

{
userId: string; // Cognito `sub`
email: string;
displayName?: string;
createdAt: string; // ISO-8601 UTC
termsAcceptedAt?: string; // ISO-8601 UTC; set once at registration
selectedPlantId?: string; // re-validated against current memberships on every GET /v1/me read
plantCount?: number; // server-computed, never client-supplied
deviceCount?: number; // server-computed, never client-supplied; see caveat below
avatar?: { // profile picture reference (stored only; never returned as is)
avatarId: string; // ULID; S3 key avatars/<sub>/<avatarId>
contentType: 'image/png' | 'image/jpeg' | 'image/webp';
sizeBytes: number;
updatedAt: string; // ISO-8601 UTC
};
}

avatar is omitted from GET /v1/me (MeResponse omits it; the legacy shape is unchanged). Readers get an AvatarView instead — the same fields plus url (signed S3 GET) and expiresAt (≤ 5 minutes) — from GET /v1/me/avatar and GET /v1/me/settings → account.avatar. Request types: CreateAvatarUploadInput { contentType, sizeBytes ≤ 2097152 } and SetAvatarInput { uploadId }. See Profile picture API.

plantCount and deviceCount are optional in the schema because they aren't stored on the profile item. Both GET /v1/me and PUT /v1/me/selected-plant always include them in the response.

Both come from getAccountSummary() (packages/core/src/repositories/users.ts), which Querys the caller's USER#<sub>/PLANT#* items, following LastEvaluatedKey until exhausted (capped at 20 pages, with a WARN log line if the cap is hit — not reachable at realistic per-account plant counts) and counting only legacy membership items: an access-index copy written by a 003/004-owned feature (copyVersion present) is excluded, so it can't inflate either count (CR-13; see Database entity shapes below).

deviceCount is summed from a deviceCount attribute on each (legacy) membership item, which avoids an N+1 per-plant query. deviceCount is maintained by feature 005 (code complete, not yet deployed): the stream router adds 1/subtracts 1 on each access-index item when a plant-device link is inserted/removed (idempotent on redelivery), and when a user gains access to a plant the access-index seeds their deviceCount by counting the plant's device links (bounded query). It is approximate: a link in flight can be counted twice and a partial failure can undercount (KI-10).

MeResponse (feature 003, FR-007 — additive extension of UserProfile)​

Returned by GET /v1/me as of 2026-10. Strictly additive onto UserProfile above — every pre-003 field keeps its exact meaning and shape; these three are new:

{
// ...every UserProfile field, unchanged...
memberships: MembershipSummary[];
defaultOrgId?: string; // ULID; absent for a brand-new account with no organisation yet
mfa: {
enrolled: boolean; // TOTP enrolled, mirrored from Cognito (15-min staleness)
requiredSomewhere: boolean; // true if ANY membership's effective MFA requirement is on
};
platformSuperAdmin: boolean; // 2026-11-05: ACTIVE scope-ALL built-in Super Admin of the PLATFORM org (UI hint)
platformAdmin: boolean; // 2026-11-05: same rule, built-in Administrator role (UI hint)
personalOrg: { orgId: string; status: "ACTIVE" | "SUSPENDED" | "CLOSED" } | null; // 2026-11-19, also while CLOSED
}

MembershipSummary (one row of memberships, also reused by GET /v1/me/context's own membership-adjacent data):

{
orgId: string; // ULID
code: string; // e.g. "OP-0001"
name: string;
kind: 'PLATFORM' | 'OPERATOR' | 'PARTNER' | 'CUSTOMER';
personal: boolean;
roleId: string; // ULID
roleName: string;
scopeKind: 'ALL' | 'REGION' | 'TAG' | 'CUSTOMER' | 'PLANTS' | 'NONE';
scopeTargetCount: number;
status: 'ACTIVE' | 'SUSPENDED'; // REMOVED memberships are never listed at all
mfaRequired: boolean; // the caller's EFFECTIVE requirement in this org — always false since 2026-11-11
}

defaultOrgId resolution (packages/core/src/access/me.ts resolveDefaultOrgId, in cse-http-be): the profile's own stored defaultOrgId wins outright when set (see GET /v1/me/context's "remembers the org" behaviour below); otherwise the first ACTIVE non-personal membership by name, else the personal org, else absent.

Side effect (FR-003): a caller holding at least one legacy OWNER plant membership gets their personal organisation lazily, idempotently created here if they don't have one yet — invisible in the response beyond defaultOrgId possibly now being set. A human-run backfill script (scripts/backfill-personal-orgs.ts in cse-http-be) can pre-warm every existing user at once instead of waiting for each one's next request; it is never run by an agent and is not wired into any deploy step.

Plant​

{
plantId: string; // ULID
name: string;
plantType: PlantType;
countryCode: string;
address?: PlantAddress;
timezone: string;
solarMode: SolarMode;
pvCapacityKwp?: number;
gridConnection: GridConnection;
electricityRate?: ElectricityRate;
hasBattery: boolean; // DERIVED (2026-11-18): a bound device has ≥ 1 battery on the TCP server; false on a new plant
status: 'ACTIVE' | 'PENDING' | 'SUSPENDED'; // always ACTIVE on creation
createdAt: string; // ISO-8601 UTC
updatedAt: string; // ISO-8601 UTC
}

Optional fields that weren't sent are absent, never null. Plants created before 2026-09-24 weren't migrated. They lack plantType, countryCode, solarMode and gridConnection (hasBattery is derived, so it is always present), and carry capacityKw and a string address instead. Clients should treat those fields as optional on read.

Where each shape is returned:

EndpointShape
POST /v1/plantsPlant exactly, with no role
GET /v1/plants/{plantId}Plant + role
PATCH /v1/plants/{plantId}Plant + role
GET /v1/plants (items)PlantListItem, a membership projection: plantId, name, pvCapacityKwp?, timezone, status, role, createdAt, updatedAt, plus address? (detail shape) and isFavorite (2026-11-17). No plantType, countryCode, solarMode, gridConnection, electricityRate or battery fields (batteryBrand was returned 2026-11-05 → 2026-11-18)

role is the caller's own role on that plant (OWNER | ADMIN | VIEWER), read from their membership item. It's not a field of the Plant schema itself, so docs/openapi.yaml models it as an optional extra property.

Device (mobile response: DeviceBindingView)​

Returned by D01 and D02 since ADR 0012: the plant ↔ serial binding, with the five shipped mobile fields only. The 005 registry fields (deviceId, type, modelId, parentDeviceId, registrationState, bindingState) are no longer returned; device detail comes from the TCP server. version is never returned.

{
serial: string; // as typed (trimmed) when bound; legacy rows keep their original spelling
plantId: string;
model?: string; // free text from the claim
label?: string;
createdAt: string; // ISO-8601 UTC
}

Removed device schemas (ADR 0012)​

The 005 registry and 007 device-operations schemas (device records, models, manufacturing records, transfers, imports, topology, commands, bulk tasks, firmware, device files, operation log) were deleted from packages/core/src/schemas.ts (change-plan phase 4); devices and commands belong to the TCP server. What remains:

  • DeviceBinding (stored binding PLANT#<plantId>/DEVICE#<serialNorm>): serial, serialNorm, plantId, label?, model?, createdAt, createdBy?, version?. See Plant devices (binding).
  • DeviceType (INVERTER, LOGGER, METER, BATTERY, OTHER) — only to accept (and ignore) the D02 type field.
  • StagedDevice — C04 staged serials.

MeContextResponse (feature 003, A03, FR-008)​

Returned by GET /v1/me/context as of 2026-10 — see Account API → GET /v1/me/context for the full endpoint writeup. One call's worth of everything the web-console shell needs to render one organisation:

{
org: Organisation; // full org metadata (E1) — see data-model.md
membership: Membership; // the caller's own membership row in `org` (E3)
levels: {
plants: Level; devices: Level; alerts: Level; commands: Level;
firmware: Level; service: Level; reports: Level; customers: Level;
team: Level; settings: Level;
};
modules: NavModuleKey[]; // nav screens levels unlock; 'settings' always present
capabilities: Capability[]; // non-level booleans (e.g. 'grid.protection.write')
badges: { pendingInvitations: number; pendingAccessRequests: number; myInvitations: number | null }; // see api/me.md#badges
mfaRequired: boolean; // this org's effective MFA requirement for the caller — always false since 2026-11-11
}

Level is 'NONE' | 'VIEW' | 'EDIT' | 'MANAGE' | 'FULL' (cumulative). NavModuleKey is 'overview' | 'plants' | 'analytics' | 'devices' | 'alerts' | 'engineering' | 'service' | 'reports' | 'customers' | 'team' | 'sharing' | 'roles' | 'audit' | 'settings' — a module is a screen unlocked by one or more of the 15 levels categories (engineering ← commands OR firmware; sharing/roles/audit ← the category of the same name, ADR 0014; overview/plants/analytics all ← plants).

levels computation per org kind (packages/core/src/access/evaluator.ts orgLevels, cse-http-be): an OPERATOR org reports the caller's role perms directly; a PARTNER/CUSTOMER org caps each category at min(role level, the relevant share/portal-relationship ceiling). Full matrix in 07-security.md §3.4 and packages/core/test/access/evaluator.matrix.test.ts.

StagedDevice​

Item of stagedDevices[] in the C04 web-create 201 and the plant workspace.

{
serialNorm: string; // normalised
serialRaw: string; // as typed
kind?: 'LOGGER' | 'INVERTER' | 'METER' | 'BATTERY'; // optional since ADR 0012, display only
connectionMethod?: 'BLUETOOTH' | 'WIFI_SETUP' | 'SERIAL' | 'QR_CODE'; // optional, display only
state: 'STAGED' | 'REGISTERED' | 'REJECTED';
reason?: string; // with REJECTED: INVALID_SERIAL | ALREADY_REGISTERED (bound to another plant)
// | PLANT_NOT_BINDABLE | FORBIDDEN
deviceId?: string; // only on rows written before ADR 0012
}

REGISTERED means the serial is now bound to the plant (a binding, as a D02 claim makes). STAGED after the create means a transient error left the entry unprocessed — claim it later with D02. A rejected entry never fails the plant. The app still registers each device with TCP over the WebSocket.

Enums​

PlantStatus​

'ACTIVE' | 'PENDING' | 'SUSPENDED'

MemberRole​

'OWNER' | 'ADMIN' | 'VIEWER'. The only role rule in code is that VIEWER can't claim a device (see Devices API). ADMIN behaves exactly like OWNER. There's no member-management endpoint, so every membership that exists today is OWNER (KI-12).

PlantStatus is only ever set to ACTIVE. Nothing sets PENDING or SUSPENDED yet, and nothing checks status when authorizing.

Error types​

Every error response produced by application code uses the same envelope. Responses generated by API Gateway itself don't: an authorizer 401, an unmatched-route 404, or a gateway 5xx is {"message": "..."} (see API overview → Gateway responses).

{
error: {
code: string; // stable, machine-readable — see the table below
message: string; // human-readable, safe to display or log
details?: unknown; // optional, shape depends on the code (see the table)
requestId?: string; // the API Gateway request id; same value as the X-Request-Id header
}
}

details and requestId are additive: they're omitted when absent (never null), and a client that ignores them keeps working. requestId is set on every error the request pipeline produces. Quote it to the backend team when reporting a problem; it's the key into the logs (see Operations → Logs).

Response headers on every Lambda response​

HeaderValue
X-Request-IdThe API Gateway request id (requestContext.requestId). Always set, on success and error
X-Correlation-IdThe client's X-Correlation-Id request header if it matches ^[A-Za-z0-9._:-]{1,64}$, otherwise the request id. An invalid value is silently replaced, never rejected
Cache-Controlno-store by default. A handler that wants caching overrides it per response

Send your own X-Correlation-Id (for example one per user action) to tie several calls together in the logs. Gateway-generated responses (authorizer 401, unmatched route 404) don't carry these headers.

Error codes​

code is a shipped contract: once a client (the Flutter app) ships checking for a specific value, that value is never changed, even if the underlying error condition is later described differently in a message.

The status for each code comes from the exhaustive ERROR_STATUS map in packages/core/src/errors.ts. Codes marked "defined, not emitted yet" exist for later features: no current route returns them, so the FE doesn't need to handle them today but should treat an unknown code by its HTTP status.

codeHTTPMeaning / FE action
UNAUTHENTICATED401The authorizer context is missing on a request that reached a handler. Only happens if a route was deployed without its authorizer. A missing/invalid token is rejected by the gateway with {"message":"Unauthorized"}, not with this code. Re-authenticate
FORBIDDEN403Authenticated but not permitted (no membership on the plant, or a VIEWER attempting a write). Don't retry
NOT_FOUND404The resource doesn't exist, or the plant's META item is missing for a member (an internal-consistency fault). A plant the caller can't access, or one that doesn't exist, is 403 FORBIDDEN (see Plants API). Also returned by the family router for an unknown route key or colon-verb
VALIDATION_FAILED422Zod validation failed (message: "Request validation failed", details = { formErrors: string[], fieldErrors: Record<string, string[]> }), the body was missing or empty ("Request body is required" — on every route with a body, lenient or strict), or a path parameter was missing. Show field errors, fix and resubmit
CONFLICT409A uniqueness constraint was violated (device serial already claimed), or a DynamoDB transaction conflicted or was cancelled with no more specific cause (message: "Please retry"). For a transaction conflict, retrying after a short delay is safe
MALFORMED_REQUEST400Strict routes only. Body present but not valid JSON, or valid JSON that isn't an object. A missing/empty body is 422 VALIDATION_FAILED instead (see above), not this code. Fix the client, don't retry
INVALID_CURSOR400Strict routes (every feature-003 list route — Team & Access, Shares, Invitations, Access-change log, Access requests): a malformed, expired, or filter-mismatched cursor. The seven legacy lenient routes still silently restart from page one instead (CR-13) — not this code
UNSUPPORTED_MEDIA_TYPE415Strict routes only. Content-Type isn't application/json (a ; charset=… suffix is allowed). Fix the client
PAYLOAD_TOO_LARGE413Decoded body over 256 KiB (262,144 bytes). Applies to every route with a body, lenient and strict. Don't retry unchanged
PRECONDITION_REQUIRED428Emitted by every feature-003 versioned route (If-Match missing, e.g. PATCH .../members/{sub}, Team & Access) and every idempotency: 'required' create route (Idempotency-Key missing, e.g. POST .../invitations, Invitations); details: { header } names which one. Fetch the resource for its ETag (versioned) or generate a key (idempotent), resend
VERSION_CONFLICT409Emitted by the same versioned routes on a stale If-Match; details: { currentVersion }. Re-fetch, merge, resubmit
IDEMPOTENCY_KEY_REUSED422Mechanism implemented (packages/core/src/idempotency.ts); reachable on any of the 6 idempotency: 'required' routes (Overview → Idempotency) if the same key is sent with a different body. Generate a new key
IDEMPOTENCY_IN_PROGRESS409Same 6 routes — the original request with this key is still running. Carries Retry-After: 1; wait and resend the same request
ALREADY_EXISTS409Emitted by several feature-003 create routes on a genuine duplicate: POST .../departments (name), POST .../shares (same grantee + identical selector), POST /v1/plants/{plantId}/access-requests (a second PENDING request). details: { entity, field }
INVALID_STATE409Emitted when an action no longer applies to the resource's current state: POST .../invitations/{inviteId} resend/revoke (not PENDING), :approve/:reject on an access request (not PENDING, or expired)
GONE410Emitted by POST /v1/invitations (accept) when the invitation's expiresAt has passed
LIMIT_EXCEEDED422Emitted when a scope/selector exceeds its per-kind cap: PATCH .../members/{sub} (scope.targets), POST .../members:bulk-assign-scope (subs ≤ 50), POST /v1/realtime/tickets (ticket size budget). details: { limit } or { field }
UNSUPPORTED_OPERATION422Emitted by PATCH/DELETE .../roles/{roleId} when the target is one of the 3 immutable system roles. Optional details: { reason }
RATE_LIMITED429Emitted on the email-grantee path of POST .../shares and on realtime-ticket issuance (per-user bucket). Retry-After header (seconds) and details: { retryAfterSec }. Wait that long, then retry
DEPENDENCY_UNAVAILABLE503A downstream AWS service throttled or was unavailable (DynamoDB ProvisionedThroughputExceededException, ThrottlingException, RequestLimitExceeded, InternalServerError, ServiceUnavailable, timeouts, or any SDK error flagged retryable / HTTP 5xx). Always carries Retry-After: 1. Retry with backoff (honour the header, add jitter, cap attempts); it is safe for reads and for writes that are idempotent
INTERNAL500Any other error (message: "An unexpected error occurred"). Logged server-side as unhandled_error with the error name, message and stack, never the request body. Known triggers: KI-7, KI-8
SESSION_REVOKED401Feature 003. Emitted by resolveRequestContext (every org-scoped route) and GET /v1/me/context when the token's auth_time precedes the account's or org membership's tokensValidAfter (end-sessions, suspend, remove, org-wide revocation) — see Authorization → Revocation. Discard cached tokens and re-authenticate
MFA_REQUIRED403Reserved — not emitted since 2026-11-11 (two-factor is the user's own choice; no route refuses for it). Feature 003, earlier behaviour: emitted when the effective MFA requirement is on and unsatisfied — only when MFA_ENFORCEMENT=on; the warn default (every stage until OQ-09 is verified) logs this instead of returning it. See Authorization → MFA
ACCOUNT_SUSPENDED403Feature 003. Emitted by resolveRequestContext/GET /v1/me/context for a caller whose membership in the active org is SUSPENDED — org-scoped only, never account-wide (suspending one org never locks a user out of another org or the mobile app). Show a suspended-access message; switching to a different org may still work
ACCOUNT_BLOCKED403ADR 0026 (RBAC v2), deployed to dev 2026-11-13. Every request of an account Crown staff blocked (POST /v1/orgs/{crownOrgId}/users/{sub}:block). Account-wide. Sign the user out and show "account blocked — contact Crown support"; nothing the user can retry. See RBAC v2
ORG_CONTEXT_REQUIRED400Feature 003. Emitted by every route resolving an org context (X-Org-Id / orgId path or query param) that received none — e.g. POST /v1/plants/{plantId}/access-requests, GET /v1/me/context, POST /v1/realtime/tickets. Prompt the caller to select an organisation, then retry with the header/param set
SCOPE_TOO_BROAD422Emitted by work-order E01 (GET /v1/orgs/{orgId}/work-orders) and E02 (…/work-orders/summary) for share-based callers whose plants cannot be enumerated or exceed the cap. details: { reason: NON_PLANT_SHARE | NO_PLANT_SHARES | TOO_MANY_PLANTS, maxPlants, narrowBy: ["plantId","technicianSub"] } — see Work orders. Narrow with plantId / technicianSub and retry
PERIOD_OUTSIDE_RETENTION422Feature 009. Not emitted by default (2026-11-02): the code returns it only when an optional floor (REPORT_RETENTION_DAILY_DAYS or REPORT_RETENTION_ALERT_DAYS) is set and the period starts before it. No stage sets them, and the deployed stacks don't pass them, so enabling one needs a CDK change. details: { floor, granularity } — floor is the earliest allowed from (YYYY-MM-DD, report timezone), granularity is DAILY (daily-rollup retention) or ALERT_HISTORY (alert-history floor). Clamp the date picker's minimum to details.floor (or shorten the period / pick a coarser template) and resubmit

Retry-After is the only extra response header an error sets — on DEPENDENCY_UNAVAILABLE always, and on RATE_LIMITED and IDEMPOTENCY_IN_PROGRESS where noted above.

This list is defined in packages/core/src/errors.ts's ErrorCode union — treat that file as the source of truth if a new code is ever added.

Database entity shapes (DynamoDB items)​

These are internal (never returned directly over HTTP — the DTOs above are derived/stripped views of them) but documented here since they shape what is and isn't possible for each endpoint. See Infrastructure → Data model for the full key-schema contract.

EntityPKSKGSI1PKGSI1SKentityTypeOther attributes
User profileUSER#<sub>PROFILE——USERuserId, email, displayName?, createdAt, termsAcceptedAt?, selectedPlantId?
MembershipUSER#<sub>PLANT#<id>PLANT#<id>USER#<sub>MEMBERSHIProle, plantId, and denormalised plant name, status, timezone, pvCapacityKwp?, createdAt, updatedAt. deviceCount is maintained by the stream router and access-index seeding, approximate (KI-10)
PlantPLANT#<id>META——PLANTEvery Plant field: plantId, name, plantType, countryCode, address? (map), timezone, solarMode, pvCapacityKwp?, gridConnection, electricityRate? (map), status, createdAt, updatedAt, createdBy? (creator's sub; 2026-11-19 for mobile creates), plus the derived batteryDeviceCount? (stream-kept, 2026-11-18; read as hasBattery = batteryDeviceCount > 0). The retired hasBattery/batteryCapacityKwh/batteryPowerKw/batteryBrand/batteryBrandOther may linger on old items until npm run migrate:strip-plant-battery runs; nothing reads them
DevicePLANT#<id>DEVICE#<serial>DEVICE#<serial>PLANT#<id>DEVICEEvery Device field: serial, plantId, model?, label?, createdAt. Planned (feature 005, not yet built): this row becomes deprecated, replaced by a registry item DEVICE#<d>/META plus a plant link — see roadmap data model
OTP throttle (email sign-in)OTPEMAIL#<sha256(lower(email))>OTP_THROTTLE———ttl only (epoch seconds, now + 60). Existence is the signal: a resend while the item exists is rejected, and a write whose own ttl has already passed is now also let through even if DynamoDB's TTL sweep hasn't reaped it yet (packages/core/src/repositories/otp-throttle.ts's condition is attribute_not_exists(PK) OR ttl < :now, not attribute_not_exists(PK) alone)

Key builders beyond the four live entities. packages/core/src/keys.ts also defines key builders (and documents access patterns 10–21) for items that later features will write: idempotency records (IDEM#<sub>), outbox messages (OUTBOX#<yyyymmddhh>#<shard>), dedup markers (DEDUP#<scope>#<id>), display-code sequences (SEQ#…) and code guards (CODE#…), facet counters (COUNT#…), search tokens (SRCH#…) and rate-limit windows (RATE#…). It also names two future indexes, GSI2 (collection index, access patterns 17 & 21) and GSI3 (facet index, pattern 18) — both sparse: no item carries GSI2*/GSI3* attributes until a feature that needs them writes them, with no backfill. Planned access patterns 10–21 (idempotency, outbox, dedup, sequences/codes, facet counters, search tokens, rate limiting, GSI2/GSI3 pages) are documented in docs/data-model.md (cse-http-be) and its companion specs/002-platform-foundation/data-model.md. GSI2 and GSI3 are both deployed on dev (GSI3 on 2026-10-13, T002-134) — they shipped in two separate deployments because CloudFormation allows only one GSI change per UpdateTable. See Infrastructure.

Key-vs-item rule. keys.relationship(), keys.customerProfile() and keys.partnerProfile() return GSI1 attributes alongside PK/SK. Passing that object as a DynamoDB Key (GetItem/UpdateItem/BatchGetItem) is rejected with ValidationException; reads narrow it with primaryKey() first (fix deployed to dev 2026-10-13).

Legacy vs. new item distinguishability (CR-13). Once a 003+ feature starts writing to a shape a legacy route also reads, two kinds of item can land next to a legacy one in the same partition: an item the new feature wrote directly, which carries schemaVersion >= CURRENT_SCHEMA_VERSION (2 today, packages/core/src/keys.ts) — for example a Device item sharing PLANT#<id>/DEVICE#<serial> with a 005 write — and a denormalised access-index copy (e.g. an additional USER#<sub>/PLANT#<id> row), which carries copyVersion instead. keys.isLegacyItem(item) returns false for either case.

This filter is now wired into listDevices (packages/core/src/repositories/plants.ts): its Query carries FilterExpression: attribute_not_exists(copyVersion) AND (attribute_not_exists(schemaVersion) OR schemaVersion < :currentSchema), so GET /v1/plants/{plantId}/devices never returns a v2 or copy device — see Devices API for the pagination trade-off that filter causes. getAccountSummary (packages/core/src/repositories/users.ts) applies the same isLegacyItem check to the memberships it fetches before computing plantCount and deviceCount, so an access-index copy no longer inflates either count (see GET /v1/me). A legacy device-claim overwriting an existing v2/copy item was never actually possible: claimDevice's transaction condition (attribute_not_exists(PK) OR attribute_not_exists(SK)) already rejects writing over any existing item at that key, v2/copy or not. getPlant has no equivalent filter — it's a single GetItem on an exact key, not a Query, so there's nothing to filter; whether a 005+ feature could replace a plant's META item with an incompatible shape is out of this filter's scope. Independently of all of this, every legacy response already goes through the allow-list projection above, so schemaVersion and copyVersion themselves never reach the APK even on an item this filter would otherwise exclude.

entityType exists purely for operators inspecting the table. Repositories strip PK, SK, GSI1PK, GSI1SK and entityType before returning an item as a DTO, and the allow-list projections above then additionally drop anything else the DTO type doesn't declare. Attributes whose value is undefined are never written (removeUndefinedValues: true), so an optional field that isn't set is absent from both the item and the response.

Every key prefix lives in packages/core/src/keys.ts, which is the authoritative contract. The access patterns (1–9) are listed in docs/data-model.md in cse-http-be. Pattern 6, members of a plant, is designed (a GSI1 query) but nothing uses it yet.

Feature 003 (Organisations, Team & Access) schemas​

packages/core/src/schemas.ts carries a large block of feature-003 Zod schemas. As of 2026-10-03, the full Team & Access surface ships: GET /v1/me and GET /v1/me/context (via MeResponse/MembershipSummary — see MeResponse above — and MeContextResponse/MeContextQuery — see MeContextResponse above and Account API → GET /v1/me/context), plus every /v1/orgs/{orgId}/… route documented in full on the Team & Access API page: org settings (B01), people (B02–B06), bulk scope assignment (B07), roles including writes (B08), departments (B09), and scope summaries (B10). Invitations (B11/B12), Shares (B13), Access requests (B15) and the Access-change log (B14) each ship separately on their own page. The whole feature-003 surface is code-complete and unit-tested as of this writing — see each page's own caution box for what's code/synth-verified only vs. captured against a real deployment.

  • Shared enums (18): OrgKind, OrgStatus, Level/LEVEL_ORDER, Category, ScopeKind, ScopeRule, MembershipStatus, ExternalLevel/ EXTERNAL_LEVEL_ORDER, RelationshipType, ShareStatus, ShareSelectorKind, GranteeKind, InvitationKind, InvitationStatus, DeliveryStatus, AccessRequestStatus, Capability, AccessLogType.
  • Entity schemas (E1–E9, E14): Organisation, OrgRelationship, Scope, Membership, Role/RolePerms, Department, Share/ ShareGrantee/ShareSelector, Invitation/InvitationDelivery, AccessRequest, AccessLogEntry/AccessLogActor/AccessLogTarget/ AccessLogImpact. (Organisation, Membership and RolePerms are already returned in full, nested inside MeContextResponse above — no standalone /v1/orgs/...-style CRUD route for them exists yet.)
  • Request/query schemas: PatchOrgInput, PatchMemberInput, MemberActionInput, BulkAssignScopeInput, CreateRoleInput, PatchRoleInput, CreateDepartmentInput, PatchDepartmentInput, CreateInvitationInput, AcceptInvitationInput, CreateShareInput, PatchShareInput, CreateAccessRequestInput, ApproveAccessRequestInput, RejectAccessRequestInput, CreateTicketInput, MembersQuery, SharesQuery, InvitationsQuery, AccessLogQuery, AccessRequestsQuery, ScopesSummaryQuery — every one is .strict(): an unknown field, or any server-owned field the route would derive itself (ids, codes, version, status, operatorOrgId, counts), is rejected rather than silently dropped. (MeContextQuery has shipped — see above.)
  • Response schemas: MemberListItem, MemberDetail, MembersSummary, RolesScreen, ScopesSummary, ShareView, InvitationView, AccessRequestView, AccessLogItem, TicketResponse, Jwk/Jwks. (MembershipSummary, MeResponse, MeContextResponse have shipped — see above.)

Full attribute-level shapes, constraints and the DynamoDB key each entity maps to are in specs/003-organizations-access/data-model.md (entities E1–E14) and docs/data-model.md (cse-http-be, access patterns #22–43); request/response field-by-field contracts per endpoint are in specs/003-organizations-access/contracts/http-api.md. Unit coverage for every schema and its error paths (scope caps, duplicate targets, bad enum, unknown field, server-owned field, email format, level ordering) is in packages/core/test/schemas.test.ts.

Feature 004 plant list schemas (not yet exposed)​

:::note Now exposed (feature 004) These schemas back live routes: the web GET /v1/plants (with X-Org-Id), GET /v1/plants/geo and GET /v1/plants/summary. See the Plants API for statuses, codes and edge cases. The heading keeps its old wording so existing links still work. :::

Feature 004 enums​

From packages/core/src/schemas.ts (append-only; never rename a value after an APK ships):

type SystemType = 'PV_ONLY' | 'PV_GRID' | 'PV_BATTERY' | 'PV_GRID_BATTERY' | 'GRID_BATTERY' | 'OTHER';
type ExportArrangement = 'NET_METERING' | 'EXPORT' | 'NO_EXPORT'; // only with GRID_CONNECTED
type GridTopology = 'ON_GRID' | 'ON_GRID_BACKUP' | 'OFF_GRID';
type PlantLifecycle = 'ACTIVE' | 'ARCHIVED' | 'DELETING'; // DELETING is never listed; reads return 410
type TagGroup = 'SEGMENT' | 'REGION' | 'SERVICE' | 'COMMERCIAL' | 'COMPLIANCE';
type TagColor = 'NEUTRAL' | 'INFO' | 'SUCCESS' | 'WARNING' | 'ERROR' | 'ACCENT';
type CustomerType = 'RESIDENTIAL' | 'COMMERCIAL' | 'INDUSTRIAL';
type CustomerStatus = 'ACTIVE' | 'CHURNED';
type PartnerRelationship = 'DEALER' | 'INSTALLER' | 'DISTRIBUTOR' | 'OM_PARTNER'; // reads/filters; writes: WritablePartnerRelationship
type WritablePartnerRelationship = 'INSTALLER'; // issue #14: partner create/PATCH only
type PartnerStatus = 'ACTIVE' | 'SUSPENDED' | 'ONBOARDING';
type StagedDeviceKind = 'LOGGER' | 'INVERTER' | 'METER' | 'BATTERY';
type ConnectionMethod = 'BLUETOOTH' | 'WIFI_SETUP' | 'SERIAL' | 'QR_CODE';
type TariffType = 'FLAT' | 'TIME_OF_USE' | 'NET_METERING' | 'NET_BILLING';
type FavoriteType = 'PLANT';
type SavedViewVisibility = 'TEAM' | 'PERSONAL';

timezone everywhere is an IANA name (Asia/Karachi); UTC offsets such as +05:00 are rejected with 422 VALIDATION_FAILED (KI-19, fixed in feature 004).

Legacy plants. Plants created by the mobile app before feature 004 are read through the legacy projection (see Response types / DTOs), and the first web PATCH (with If-Match: "0") rewrites one to the current shape. The whole fleet can be converted at once with the human-run legacy plant migration.

PlantListFilters​

These filters are shared by the web list and the geo query. None of them is a telemetry field. Repeatable params can be sent once or repeated, and the server wraps a single value in an array.

FieldTypeRule
lifecycleACTIVE | ARCHIVEDoptional
plantTypePlantType[]1–5 values
countryCodeCountryCodeoptional
regionTagId, tagIdULID[]1–5 values each
customerOrgId, installerOrgIdULIDoptional
capacityMin, capacityMaxnumber 0–100000min ≤ max
createdFrom, createdToISO-8601 datetimefrom ≤ to
operatorOrgIdULIDrequired when X-Org-Id is the PLATFORM org; forbidden otherwise

WebPlantListQuery​

This is LazyListQuery (limit 1–50, default 15 on the first page and 10 with a cursor, opaque cursor) plus PlantListFilters, with three extra fields:

  • favorite=true
  • q: 2–64 characters after trimming
  • sort: name, -name, createdAt or -createdAt

The schema is strict, so unknown params are rejected. sort cannot be combined with q.

WebPlantListResponse​

The response is { items, nextCursor?, refs }. Each item is a WebPlantListItem. Every item carries operatorOrgId (the owning org, ADR 0016). When q was sent, an item can also carry matchedField, one of name, code, customer, city, region or tag. The response has no totals and no page numbers.

GeoQuery, GeoPlantRow, GeoPlantsResponse​

GeoQuery takes the PlantListFilters plus limit (1–1000, default 1000) and cursor. It does not accept sort, q or favorite, and it is strict.

Each GeoPlantRow has these fields:

  • plantId, code, name
  • latitude, longitude
  • regionTagId (optional)
  • plantType (optional)

Plants without coordinates are skipped. The response is { items, nextCursor? }.

PlantsSummaryResponse​

Counts come from facet counters and are approximate, so approximate is always true.

Fields always present:

  • approximate, scoped, refs
  • byRegionTag, byTag, byCustomer

Optional fields:

  • plantCount, capacityKwp, expectedAnnualYieldKwh
  • byLifecycle, byPlantType, byCountry, byInstaller

Each by* field is a map from key to integer count. byCustomer and byInstaller hold only the top 50. A scoped caller (scoped: true) gets only byTag, byRegionTag and byCustomer for their own targets; the other fields are left out.

Error codes (plant list)​

  • VALIDATION_FAILED: a bad or unknown param. A sort the chosen list path doesn't allow returns details.allowed.
  • INVALID_CURSOR
  • SCOPE_TOO_BROAD

Event payload builders (packages/core/src/plants/events.ts)​

These builders create outbox envelopes. Plant events use aggregate PLANT, subject plant/<plantId> and seq = the plant version. Fields that are undefined are left out of the payload; they are never sent as null.

Eventdata
plant.upserted.v1plantId, code, name, operatorOrgId, customerOrgId, installerOrgId, sorted tagIds, regionTagId, timezone, countryCode, pvCapacityKwp, expectedAnnualYieldKwh, gridConnection, plantType (always RESIDENTIAL/COMMERCIAL/INDUSTRIAL; stored legacy values mapped), commissionedOn, systemType, tariff (when stored: currency (always present, ISO 4217), tariffType, importRate, exportRate, touSchedule[] of {days, start, end, rate}, effectiveFrom; optional fields omitted, never null. The key is omitted when the plant has no stored tariff, never null. Since 2026-11-23 every emitter re-reads the stored SETTINGS#TARIFF and sends it — the TCP projection treats an absent tariff as "none" and clears its copy, and the TCP console's get_plant_overview prices savings with it), lifecycle, version, ownerUserSub (2026-11-20: the plant's stored owner — the creator, or the end user assigned at create / by a share; the unsharer after an unshare; non-null for every plant with an owner), createdByUserSub (2026-11-19: the creator's Cognito sub, on every event when the plant stores it; absent for older mobile plants), createdAt (2026-11-25, console request P9: the plant's creation time, ISO-8601 UTC, on every event when stored and parseable; absent otherwise). batteries (2026-11-19 create batteries) was removed 2026-11-20 — plant create takes no battery data. hasBattery and batteryCapacityKwh were removed 2026-11-18 (battery data is per device on TCP); plantType and commissionedOn were added 2026-10-27 (T009-092); optional latitude/longitude (both present only when the stored address has valid coordinates; rounded to 2 decimal places, about 1 km) added 2026-11-02; optional top-level city/region (B-3, 2026-11-19: from the stored address, trimmed, each present only when non-empty; never the street or a legacy string address) added 2026-11-19; additive, so the event stays v1
plant.alert-rules.updated.v1plantId, underperformance, communicationLoss, batteryTemperature, notifyEmail, escalateCriticalSms, version
plant.archived.v1 / plant.restored.v1plantId, at, version
plant.deletion.requested.v1plantId, code, deviceIds, deadline, version
org.upserted.v1003's org payload (aggregate ORG)
access.revoked.v1built by accessRevokedEvent, following docs/events/access.revoked.v1.schema.json

Invitation edit (N-47)​

  • AccessLogType gains INVITATION_UPDATED, written by PATCH /v1/orgs/{orgId}/invitations/{inviteId} when a pending invitation's role, scope or department changes.
  • Invitation and access-request list rows carry version (int, N-45) — the If-Match value.

Feature 004 additions: customers and partners​

  • AccessLogType gains CUSTOMER_PORTAL_CHANGED (any customer portalLevel change), CUSTOMER_CLOSED (customer :close) and PARTNER_SUSPENDED (partner status → SUSPENDED). See Customers and Partners.
  • access.revoked.v1 reason gains CUSTOMER_CLOSED, PORTAL_NARROWED (customer portalLevel lowered) and PARTNER_SUSPENDED. In all three cases scope is ORG and orgId is the customer or partner org.
  • 2026-11-03 (R-3a): access.revoked.v1 reason gains BUSINESS_NARROWED (scope: ORG, orgId = the Business org) when a Business limit is lowered. New types BusinessLimit, BusinessSummary and PutBusinessLimitInput; CreateBusinessInput gains optional permsLimit; AccessLogType gains BUSINESS_LIMIT_CHANGED.
  • 2026-11-03 (ADR 0016): WebPlantListItem gains operatorOrgId (the owning org, always present); GeoPlantRow gains optional operatorOrgId; Refs.orgs[*] gains optional personal: true (a personal org); PlantListFilters.operatorOrgId becomes optional in the platform org for the built-in Super Admin / Administrator (absent = every org, see Platform-wide list).
  • 2026-11-03 (R-5): Plant / PlantDetail / WebPlantListItem gain optional installedBy { sub, displayName, at } and assignedInstaller { sub, displayName }; PlantListFilters gains assignedInstallerSub; new AssignPlantInstallerInput { sub: string | null } and PlantInstallerChange { at, by, from, to }; AccessLogType gains PLANT_INSTALLER_CHANGED; access.revoked.v1 reason gains INSTALLER_REASSIGNED (scope: USER, plantIds); plant.upserted.v1 gains optional assignedInstallerSub. See Assigned Installer.
  • 2026-11-13 (issue #14, not deployed): CreateCustomerInput gains optional operatorOrgId (ULID; required on the Crown org, see Crown org: any customer); CustomerListQuery gains hasPlants (true only); new WritablePartnerRelationship (INSTALLER) for CreatePartnerInput / UpdatePartnerInput.relationship; BusinessesQuery gains status and q; BusinessSummary gains plantCount, customerCount, memberCount and approximate: true (see Businesses list).
  • 2026-11-14 (RBAC v2 follow-ups): WebPlantListItem and GeoPlantRow gain optional blocked: true (a plant frozen by Block B); BusinessSummary gains creatorSub: string | null and orgVersion (the If-Match of the lifecycle routes — version stays the limit's); new details.reason MEMBER_IN_ANOTHER_BUSINESS (409 CONFLICT on :reopen); new routes for carried-in shares reuse the ShareView / shares-list shapes. TicketResponse gains frozenPlantIds: string[] and the ticket gains the optional claim xp (Realtime).
  • 2026-11-17 (web console data-lookup request, all additive and optional): WebPlantListItem gains timezone; the mobile PlantListItem gains address (detail shape) and isFavorite; WorkspaceResponse.plant gains role (as on the mobile detail); DashboardResponse.setupIncomplete is also sent to scoped members of an OPERATOR org (Setup incomplete); TechnicianView gains teamName and regionLabel; MaintenancePlanView gains teamName.
  • 2026-11-19 (one account per user, RBAC v2): MeResponse gains personalOrg: { orgId, status } | null; BusinessSummary gains installerCount (exact); BusinessLifecycleResult gains optional membersReturned and membersRemaining (:close only); new details.reason NOT_A_MEMBER (403 FORBIDDEN on org selection); NOT_BUSINESS_CREATOR retired (a Business never closes itself — PLATFORM_ONLY).
  • 2026-11-19 (plant transfer, Plants): new PlantTransferInput { plantId, email } and PlantTransferResponse { plantId, version, mode: BUSINESS | PLATFORM, operatorOrgId, previousOperatorOrgId, receiverSub, customerSub?, ownerUserSub, joinedBusiness }; removed PlantHandoverInput, PlantHandoverResponse and Invitation.handoverPlantIds. AccessLogType gains PLANT_TRANSFERRED (PLANT_HANDED_OVER / PLANT_HANDOVER_OFFERED are no longer written). New details.reason: USER_NOT_REGISTERED (404), USER_IN_ANOTHER_ORG, ALREADY_OWNER, RECEIVER_CHANGED (409); HANDOVER_PENDING retired. Plant META gains ownerUserSub (stored owner, sent as plant.upserted.v1 ownerUserSub).
  • 2026-11-20 (ADR 0029, Plants → ownership): CreatePlantInput / CreatePlantWebInput no longer take battery data (batteries and the flat battery fields are accepted with any value and dropped; CreateBatteryItem and BatteryBrand removed); PlantDetail documents optional ownerUserSub and customerSub; PlantTransferInput gains optional businessOrgId (Crown staff only); new PlantUnshareInput { plantId } and PlantUnshareResponse { plantId, version, mode, operatorOrgId, previousCustomerSub, ownerUserSub }; AccessLogType gains PLANT_UNSHARED. New details.reason: END_USER_CANNOT_UNSHARE (403), NOT_SHARED, PLANT_IN_PERSONAL_ORG, PLANT_BROUGHT_IN (409).
  • 2026-11-20 (recipient check, Plants): new PlantTransferCheckInput (= PlantTransferInput), PlantTransferCheckReason (enum of the transfer's receiver-side reason codes plus USER_NOT_REGISTERED) and PlantTransferCheckResponse { found, recipient?: { displayName | null, email }, eligible, reason | null, message | null } (message added 2026-11-26: the transfer's error.message for reason, safe to show).
  • 2026-11-30 (Business invite flow, Invitations → account check): new AccountCheckPurpose (PLANT_TRANSFER | BUSINESS_OWNER | INVITATION), AccountCheckInput { purpose, email, plantId?, businessOrgId?, roleId? } (strict; per-purpose required / refused fields → 422), AccountCheckReason (PlantTransferCheckReason + ALREADY_IN_BUSINESS, ALREADY_MEMBER, CROWN_STAFF) and AccountCheckResponse (the PlantTransferCheckResponse shape with the wider reason). New details.reason: BUSINESS_ROLE_VIA_CREATE_ONLY (403); POST …/businesses adds USER_NOT_REGISTERED (422), ACCOUNT_BLOCKED (403), ALREADY_IN_BUSINESS / INVITATION_PENDING / CROWN_STAFF / MOVE_IN_PROGRESS (409).
  • 2026-11-27 (ADR 0032), share a plant with a business:
    • BusinessLookupInput { joinCode } → BusinessLookupResponse { orgId, name }.
    • CreateBusinessShareInput { businessOrgId, level? (VIEW), note? }, strict.
    • BusinessShareView { shareId, plant { plantId, name, city?, capacityKwp? }, business { orgId, name }, from { displayName }, level, status, note?, createdAt, expiresAt, decidedAt?, endedAt?, endedBy?, version }.
    • status: PENDING | ACTIVE | DECLINED | CANCELLED | EXPIRED | REVOKED.
    • endedBy: OWNER | BUSINESS | JOINED_BUSINESS | PLANT_DELETED.
    • Queries: MyBusinessSharesQuery { status?, plantId?, limit, cursor? } and IncomingPlantSharesQuery { status = PENDING, limit, cursor? }.
    • Share.origin?: BUSINESS_SHARE.
    • New inbox kinds PLANT_SHARE_* and link type PLANT_SHARE.
    • New access-log types BUSINESS_SHARE_REQUESTED / _DECIDED / _ENDED.
    • See the guide.

ADR 0014 phase 2a: PermsLimit​

  • PermsLimit = RolePerms made partial and .strict(): any subset of the 15 Category keys, each a Level (NONE/VIEW/EDIT/MANAGE/FULL). Unknown key → 422 VALIDATION_FAILED.
  • Used as Share.permsLimit (CreateShareInput, PatchShareInput — PATCH also accepts null, ShareView) and OrgRelationship.portalPermsLimit (customer create/patch bodies — PATCH also accepts null, CustomerProfile, overview permissions). Returned only when set; {} is never stored.
  • Effective ceiling = per category min(tier ceiling, limit) (ceilingOf). See Roles & permissions.

Service / O&M (feature 006)​

:::warning ADR 0023 additions not deployed These schemas are in packages/core/src/schemas.ts. The routes that use them are in the cse-http-be-<stage>-api-service stack (Q27). The work-order lifecycle v2 additions marked ADR 0023 below are built but not deployed. See work orders and plans, history, roster. :::

Enums​

EnumValues
WorkOrderStatusADR 0023 (lifecycle v2; built, not deployed): NEW (Draft), REJECTED, ASSIGNED, ACCEPTED, IN_PROGRESS, WAITING (On Hold), COMPLETED (awaiting verification), VERIFIED, REOPENED, CLOSED, CANCELLED. Open = every status except CLOSED and CANCELLED. Pre-v2 items are read in v2 terms until the backfill (ASSIGNED + acceptance → ACCEPTED, COMPLETED + businessClosure → CLOSED). SCHEDULED was retired on 2026-11-04 (ADR 0019): stored values are read as ASSIGNED. See the status model
WorkOrderPriorityCRITICAL, HIGH, MEDIUM, LOW (rank order)
WorkTypeCORRECTIVE_REPAIR, COMPONENT_REPLACEMENT, PREVENTIVE_MAINTENANCE, COMMISSIONING, INSPECTION, CLEANING, FIRMWARE_CONFIGURATION, SITE_SURVEY
WorkOrderSourceSERVICE, PLANT, DEVICE, ALERT, PLAN, SERVICE_REQUEST (PLAN set by the plan worker; SERVICE_REQUEST only on orders created from a service request before ADR 0023 retired them; user input rejects both)
ServiceRequestStatusSUBMITTED, ACCEPTED, DECLINED (WO-7). Stored items only: the routes were removed by ADR 0023 D12
WaitingReasonCUSTOMER_UNAVAILABLE, PARTS_UNAVAILABLE, INSTALLER_UNAVAILABLE, AWAITING_APPROVAL, SITE_INACCESSIBLE, INVESTIGATION_REQUIRED, OTHER (ADR 0023 D3). For one release the input also accepts PART → PARTS_UNAVAILABLE, APPROVAL → AWAITING_APPROVAL, SITE_ACCESS → SITE_INACCESSIBLE; responses always carry the new values
HoldFromStatusASSIGNED, ACCEPTED, IN_PROGRESS — waiting.holdFrom, the status :resume restores (ADR 0023)
WorkOrderNoteKindGENERAL (default), FINDING, DIAGNOSIS, WORK_PERFORMED, MATERIAL, ISSUE, INSTRUCTION_REQUEST (E08, ADR 0023 D5)
CancelReasonDUPLICATE, WITHDRAWN, NOT_A_FAULT, OTHER
CompletionResultRESOLVED, FOLLOW_UP_REQUIRED, NO_FAULT_FOUND, REPEAT_VISIT
SlaStateNO_TARGET, ON_TARGET, PAST_TARGET (open); NO_TARGET, MET, MISSED (closed) — derived only
AlertSeverityCRITICAL, WARNING, INFO (client upper-cases TCP severities)
VisibilityINTERNAL, CUSTOMER
AttachmentKind / AttachmentStatusPHOTO, DOCUMENT, SIGNATURE / PENDING, READY, DELETED
WorkOrderEventKindCREATED, PRIORITY_SET, ASSIGNED, REASSIGNED, UNASSIGNED, SCHEDULED, RESCHEDULED, STARTED, WAITING, RESUMED, NOTE, FIELDS_CHANGED, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, CHECKLIST_UPDATED, COMPLETED, CANCELLED, REOPENED, ACCEPTED, DECLINED, CLOSED (WO-1/WO-2), VERIFIED, COMPLETION_REJECTED, HOLD_REQUESTED (ADR 0023 D8)
PlanStatusACTIVE, PAUSED (stored), ENDED (derived)
ContractKindOM_CONTRACT, MANUFACTURER_WARRANTY, PERFORMANCE_WARRANTY, EXTENDED_WARRANTY
ContractComponentPLANT, INVERTERS, MODULES, BATTERIES, LOGGERS
ContractStatusACTIVE, EXPIRED, NOT_CONTRACTED, QUOTE_AVAILABLE
SkillINVERTER, BATTERY, LOGGER, METERING, HV, COMMISSIONING, CLEANING, INSPECTION
HistoryOutcomeCOMPLETED (since ADR 0023: a CLOSED order), CANCELLED
InboxNotificationKind (work orders)WORK_ORDER_ASSIGNED, WORK_ORDER_STATUS, WORK_ORDER_UNASSIGNED, WORK_ORDER_ACCEPTED, WORK_ORDER_DECLINED, WORK_ORDER_COMPLETED; ADR 0023 adds WORK_ORDER_STARTED, WORK_ORDER_PROGRESS, WORK_ORDER_COMPLETION_REJECTED, WORK_ORDER_VERIFIED, WORK_ORDER_CLOSED, WORK_ORDER_CANCELLED, WORK_ORDER_ON_HOLD, WORK_ORDER_RESUMED, WORK_ORDER_HOLD_REQUESTED. SERVICE_REQUEST_SUBMITTED / SERVICE_REQUEST_DECIDED stay in the enum but are no longer produced. Recipients: notifications
InboxNotificationKind (other)ACCESS_REQUEST_DECIDED, SHARE_GRANTED, REPORT_READY, since 2026-11-23 INVITATION_RECEIVED (invitation notification), and since 2026-11-26 JOIN_REQUEST_RECEIVED, ADDED_TO_BUSINESS (membership notices)
InboxLinkTypeWORK_ORDER, ACCESS_REQUEST, SHARE, REPORT, SERVICE_REQUEST, INVITATION (2026-11-23), JOIN_REQUEST, ORG (2026-11-26, ADR 0031)
InboxInvitationRef{inviteId, org: {orgId, name}, role: {name} | null} — on INVITATION_RECEIVED items only

Value shapes​

ShapeFields / rules
Money{amount 0…1e9, currency ISO-4217}; ≤ 2 dp (≤ 3 for BHD, IQD, JOD, KWD, LYD, OMR, TND); must match the org currency
ActorRef{kind: USER|SYSTEM, sub?, displayName, orgId?, role? ≤ 120, viaPlatform?, system?: {kind: MAINTENANCE_PLAN, planId, planCode}}. role (ADR 0023 D8) is the actor's role name in orgId at write time, on work-order events; absent on older records. viaPlatform (2026-11-12): Crown staff through platform access, returned as displayName: "Crown Support" with no sub/orgId/role to readers outside the Crown org
AlertRef (input){alertId 1–64 [A-Za-z0-9_.:-], code?, title?, severity?, deviceKey?} — format only
WorkOrderAlert (stored)AlertRef + linkedAt, clientSupplied: true
Part{partId, name ≤ 120, sku? [A-Z0-9-] ≤ 40, qty 1–999, unitCost: Money, status: REQUESTED|FITTED}
ActionEntry{actionId, text ≤ 500, at, by: ActorRef}
ChecklistItem{itemId, text ≤ 200, done, doneAt?, doneBySub?}
Completion{diagnosis? ≤ 4000, workPerformed? ≤ 4000, completionNotes? ≤ 4000, resolution? ≤ 4000, result, hoursOnSite? 0–999.9, downtimeMinutes? 0–525600, completedAt, completedBy, signature?: {attachmentId, signerName, signedAt}}. :complete requires diagnosis and workPerformed (ADR 0023 D4) and stores resolution = workPerformed for older readers; pre-v2 completions carry only resolution
CompleteInput (:complete){diagnosis, workPerformed, completionNotes?, resolution? (deprecated alias of workPerformed), actualCost? (optional since v2), result, hoursOnSite?, downtimeMinutes?, signature?} — missing required fields → one 422 with details.fields
VerifyInput / RejectCompletionInput / RequestHoldInput{notes? 1–1000} / {reason 1–1000, instructions? 1–4000} / {reason: WaitingReason, note? 1–1000} (ADR 0023)
CloseInput / AssignInput{remarks? 1–1000, note? (deprecated alias)} / {technicianSub | null, teamId?, reason? 1–1000} (reason required when reassigning, ADR 0023)
WorkOrderVerification / CompletionRejection / HoldRequest{result: VERIFIED, verifiedAt, verifiedBy, notes?} / {rejectedAt, rejectedBy, reason, instructions?} / {requestedAt, requestedBy, reason, note?} (ADR 0023)
WorkOrderCompletionEntry / WorkOrderAssignmentEntryE04 completions[] / assignments[], derived from the timeline (ADR 0023 D4, D7) — see E04
NoteMaterial{name 1–200, quantity? > 0, serialNumber? 1–64, replacedSerialNumber? 1–64} — only on a MATERIAL note
PreferredDateYYYY-MM-DD, a real calendar date (E03/E05 preferredDate, ADR 0023 D6)
IssueCategoryprovisional (ADR 0023 D6, O5): NO_GENERATION, LOW_GENERATION, INVERTER_FAULT, BATTERY_ISSUE, COMMUNICATION_LOSS, PANEL_DAMAGE, WIRING_ELECTRICAL, GRID_OR_METER, CLEANING_REQUEST, OTHER. The reported issue; WorkType stays the job type
WorkOrderCode / PlanCodeWO-YYYY-NNNN (per operator org) / MP-NNN
WorkOrdersee E04; limits: parts ≤ 50, actions ≤ 50, checklist ≤ 30, attachments ≤ 30. ADR 0023 adds assignedAt, holdRequest, verification, lastCompletionRejection, instructions ≤ 4000, preferredDate, issueCategory, and waiting.holdFrom / heldBy
CreateWorkOrderInput / UpdateWorkOrderInput (ADR 0023 additions)E03: customerOrgId?, instructions? (MANAGE), preferredDate?, issueCategory?. E05: instructions, preferredDate, issueCategory, actualCost (null clears; instructions and actualCost need MANAGE)
ListWorkOrdersQuery (ADR 0023 additions)createdFrom, createdTo, plannedFrom, plannedTo, awaitingAcceptanceSince (ISO-8601 UTC); sort adds createdAt (-createdAt no longer needs plantId)
WorkOrderSummary.metrics (ADR 0023 additions)draft, rejected, awaitingAcceptance, accepted, onHold, awaitingVerification, verified, reopened, closed, cancelled; inProgress is IN_PROGRESS only (breaking)
WorkOrderRowlist projection (E01): id, code, version, title, status, priority, workType, source, plant, customerName, device, technician, teamId, dates, sla, costDisplay?, alert?, planId?, matchedField?
Recurrence, PlanScopeRule, MaintenancePlansee E11
HistoryTiles{visits, hoursOnSite, recordedCost?[], neededReturn, neededReturnPct, truncated, approximate?}
TechnicianView, Team, ServiceContractsee E10/E13

Notifications (feature 008, planned)​

Defined in packages/core/src/schemas.ts; see the Notifications API.

Schema / enumValues / use
NotifyChannelPUSH, EMAIL, SMS, WHATSAPP (ActiveNotifyChannel = PUSH, EMAIL)
NotifyOnRAISED, RESOLVED
ChannelUnavailableReasonPUSH_SENDER_NOT_READY, EMAIL_PROVIDER_NOT_READY
NotificationSettingsCapabilitynotificationSettings.view, notificationSettings.edit, notificationRules.view, notificationRules.edit, notificationDeliveries.view
SYSTEM_RULE_LOCKED_FIELDSname, severity, scope, schedule, enabled
RegisterPushTokenInput, PushTokenView, PushTokenIdA09
NotificationRule, CreateNotificationRuleInput, UpdateNotificationRuleInput, PreviewNotificationRuleInputG01, G03
NotificationSettings, PutNotificationSettingsInput, NotificationSettingsView, NotificationChannelViewG02. Issue #14 (2026-11-13, not deployed): stored settings gain workOrderAssignment: { push } (default true); PUT accepts it optionally; the view adds workOrderAssignment: { inApp: true, push, audience: "ASSIGNEE", timing: "IMMEDIATE" }
WorkOrderAssignmentDefault{ push: boolean }, strict (issue #14)
NotifyAudienceV1, NotifyUserV1, NotifyUserDeletedV1, NotifyOrgSettingsV1, NotifyPushRequestedV1, NotifyReconciliationCompletedV1, NotifyEndpointInvalidV1, NotifyEmailRequestedV1Bus events
AlertWorkOrdersPathG05 path: alertId ^[A-Za-z0-9_-]{1,64}$
AlertWorkOrderLinkG05 row (assignee, dueAt optional; max 20 rows)
NotifyRecomputeRequestInternal recompute/reconcile message

Account settings (feature 010)​

Defined in packages/core/src/schemas.ts; see the Account settings API.

Schema / enumValues / use
ThemeLIGHT, DARK, SYSTEM
DensityCOMFORTABLE, COMPACT
LandingPageOVERVIEW, PLANTS, ALERTS, SERVICE, ANALYTICS
EnergyScalingAUTO, KWH
DateFormatD_MMM_YYYY, DD_MM_YYYY, YYYY_MM_DD
ClockFormatH24, H12
WeekStartMONDAY, SUNDAY
HhMm / QuarterHourTimeHH:mm; quiet-hours times must fall on a quarter hour
NotificationPreferences, UserPreferences, UserPreferencesView, UpdatePreferencesInputA04 get/patch (deep-partial, strict)
UpdateProfileInput, ProfileAccountViewA05
SessionClientKindWEB, MOBILE, SERVER
DeviceClassDESKTOP, PHONE, TABLET, UNKNOWN
SessionStatusACTIVE, SIGNED_OUT, ENDED_BY_SIGN_OUT_EVERYWHERE, EXPIRED. Lists filter out expired sign-ins (issue #29, 2026-11-12, not deployed), so a returned item is never EXPIRED
SessionView, SessionListViewA06. SessionView gained optional ipAddress and required expiresAt (2026-11-12, not deployed). deviceLabel falls back to "Crown mobile app" / "Web browser" by client kind instead of "Unknown device" (issue #29)
SettingsViewA-010-01 bundle (security.mfa.status: ENABLED, DISABLED, UNKNOWN)
PasswordChangeReportResponse, DisableMfaResponse, EndAllSessionsResponseA-010-05, A-010-06, A07
EndOtherSessionsResponse { ended: number }POST /v1/me/sessions:end-others (S-1, 2026-11-12, not deployed)
StartPhoneChangeInput, VerifyPhoneChangeInputDefined for US6 phone change, which is not built: no route uses them

Web console additions​

See Web console additions (N-37 … N-51) for the newer, not-yet-deployed fields and routes on this area.