Search, lookup & catalog (discovery family)
Routes that resolve or search across entities by something other than their
own id/path — "discovery" is this family's name in lib/routes.ts
(family: 'discovery', one shared Lambda). All three routes in this family
ship in this feature (002): GET /v1/lookup (A13), GET /v1/search/suggestions
(A12) and GET /v1/catalog/{name} (A14).
:::note Deployed on dev
These routes are live on dev (verified 2026-10-13). Every example below is
illustrative, derived from the schema and handler code, not a captured
execution.
:::
GET /v1/lookup — Resolve a display code
Purpose: resolves a display code (PL-0518, WO-2026-0498) to its
entity — for deep links and pasting a code into global search. Display
codes are short, human-typeable identifiers allocated by codeGuard
(packages/core/src/codes.ts, FR-030); this route is the one place that
turns one back into an entity reference.
- HTTP method:
GET - Endpoint:
/v1/lookup - Authentication: Required (Cognito bearer token — any of the four
clients:
flutter-app-default,flutter-app-remembered,web-console, andserver-adminindevonly). - Authorization: Per-entity, via the prefix lookup type that resolved
the code. Each registered type supplies its own
authorize(ctx, entityId, orgId)(registerLookupType,packages/core/src/codes.ts) — this route has no authorization logic of its own beyond calling it. 004 registers its display-code prefix types and 006 registersWO-(work orders). The 005 device-id/serial resolvers and the 007OP-/BLK-/FW-types are no longer registered (ADR 0012 phase 2). - Side effects: none. Pure read.
- DynamoDB calls: one strongly consistent
GetItemon the code guard item (CODE#<code>/GUARDfor a platform-wide type, orCODE#<operatorOrgId>#<code>/GUARDfor a per-operatorWO-type), plus whatever reads the matched type's ownauthorizecallback makes (not controlled by this route).
Request
Headers
| Header | Required | Value |
|---|---|---|
Authorization | Yes | Bearer <token> |
X-Org-Id | Only to resolve a per-operator (WO-) code | The caller's active operator organisation, as a ULID |
Path parameters: none.
Query parameters
| Param | Type | Required | Validation |
|---|---|---|---|
code | string | Yes | Trimmed, max 80 chars, /^(?:[A-Z]{1,4}(-\d{4})?-\d{2,}|[A-Z0-9._][A-Z0-9._ -]{2,})$/i — a display code (PL-0518, WO-2026-0498), a device id (26-char ULID) or a device serial as entered (005, T005-108). Upper-cased server-side before matching |
This is a strict route: code is the only accepted query parameter —
any other one (e.g. ?code=PL-0518&foo=bar) is rejected, whether or not
code itself is valid.
Request body: none.
Response
Structure (LookupResult — see
Types & schemas):
{
type: string; // the resolved entity's registered lookup type, e.g. "plant"
id: string; // ULID of the resolved entity
code: string; // the code, normalised (trimmed, upper-cased) — may differ from what was sent
orgId: string; // owning organisation of the resolved entity
}
Successful response — illustrative example
{ "type": "plant", "id": "01J9Z4A1B2C3D4E5F6G7H8J9K0", "code": "PL-0518", "orgId": "01J9Z3K8N4R6X2QYV7M1WB0T3F" }
Failure response — not found (illustrative)
{ "error": { "code": "NOT_FOUND", "message": "Code not found", "requestId": "Abc123Xyz=" } }
This EXACT body and status is returned for every one of: an unparseable
code, a code whose prefix has no registered type, a WO- code sent with no
(or the wrong) X-Org-Id, a code with no guard item at all, and a code the
caller's authorize callback denies. See Edge cases below — this is
deliberate non-disclosure, not an accident.
Failure response — validation failure (illustrative)
A missing or malformed code:
{ "error": { "code": "VALIDATION_FAILED", "message": "is not a recognised display code, device id or serial format", "details": { "formErrors": [], "fieldErrors": { "code": ["is not a recognised display code, device id or serial format"] } }, "requestId": "Abc123Xyz=" } }
An unknown query parameter:
{ "error": { "code": "VALIDATION_FAILED", "message": "Unknown query parameter", "details": { "unknown": ["foo"] }, "requestId": "Abc123Xyz=" } }
HTTP status codes
| Status | code | When | FE guidance |
|---|---|---|---|
| 200 | — | Code found, and the resolved entity's authorize allowed it | Use the type/id to route (e.g. open the matching plant screen) |
| 401 | — (gateway body {"message":"Unauthorized"}) | Missing/invalid/expired token, or a client not accepted by the authorizer | Re-authenticate / refresh the token |
| 401 | SESSION_REVOKED | The token is valid but its session was revoked (standard { error: { code, message } } envelope, from the Lambda, not the gateway) | Sign the user in again |
| 403 | FORBIDDEN / ACCOUNT_SUSPENDED | X-Org-Id names an organisation the caller is not a member of (or the membership is suspended) — checked before any lookup/search runs (004, T004-1212) | Don't retry; switch to an org the user belongs to |
| 404 | NOT_FOUND | No guard item, unregistered type, WO- code with no/wrong org context, or denied — all identical (non-disclosure) | Show a generic "code not found" message. Never tell the user which specific case applied — the server doesn't either |
| 400 | VALIDATION_FAILED | code missing or fails its pattern (details.fieldErrors), or an unknown query parameter was sent (details.unknown) | Fix the client request — this is a client bug, not retryable as-is |
| 500 | INTERNAL | Unexpected server error | Retry once; if it persists, report it |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB throttled/unavailable | Retry with backoff; honor Retry-After if present |
Edge cases
- Non-disclosure is deliberate and total. An unknown code, a code
belonging to a type nobody registered, a
WO-code looked up without (or with the wrong) organisation context, and a code that exists but the caller isn't authorized to view all return the exact same404 NOT_FOUNDbody. Do not try to distinguish these cases in the UI from the response alone — there is nothing in the response that does. - Platform-wide vs. per-operator codes.
PL-andRPT-YYYY-are platform-wide: they resolve with no org context at all. OnlyWO-(work order) codes are per-operator — resolving one requiresX-Org-Idto be the same operator organisation whose sequence issued it; a different (or missing) organisation is404, not403(same non-disclosure reasoning as above). X-Org-Idformat. As implemented in 002, a malformedX-Org-Idvalue is silently treated as absent (buildContextonly accepts a well-formed 26-character ULID and drops anything else) — it is not rejected with a400. Full validation/trust of this header is feature 003's job; don't rely on the server rejecting a malformed value today.- Registered lookup types (004).
plant(PL-),customer(CU-),partner(PB-) andtag(TG-) are registered inpackages/core/src/plants/lookup.ts.plantre-checks VIEW on that exact plant;customer/partnerneedcustomersaccess andtagneedsplantsaccess in the owning org. A caller without access gets the same404 NOT_FOUNDas an unknown code (non-disclosure).OP-,BLK-andFW-codes always return404(their 007 types were removed by ADR 0012);WO-is registered by 006 (below). - Membership check on
X-Org-Id. If the optionalX-Org-Idis sent and the caller is not a member of that org, the response is403, not404— the header is the caller's own claim, so this discloses nothing about the code. - Device lookup — removed (ADR 0012 phase 2). The prefix-less
device(deviceId) andserialresolvers are no longer registered: a deviceId or a serial still passes thecodepattern but always returns404 NOT_FOUND. Devices are served by the TCP server over the WebSocket. - Work-order lookup (006, T006-130).
WO-YYYY-NNNNcodes are registered as typeworkOrderinpackages/core/src/service/lookup.ts(loaded through@cse/core, so it is active in the routedGET /v1/lookupfunction from the next ApiStack deploy — not yet executed against any stage). Codes are per operator: the guard is read under the caller's ACTIVE operator-org context only (X-Org-Id/ current context); no or a different context →404. The resolved order is then re-authorized with E04's rule (service ≥ VIEW on the order's plant); any denial is the same404.type: "workOrder",id=workOrderId. The work-order routes themselves are registered in code (stackcse-http-be-<stage>-api-service) and routed (work orders; observed answering ondevon 2026-10-28).MP-plan codes are deliberately not resolvable globally. - Code normalisation. The
codein a200response is the normalised form (trimmed, upper-cased) the server matched against, not necessarily byte-identical to what was sent — a client that sentpl-0518gets backPL-0518.
GET /v1/search/suggestions — Global search typeahead
Purpose: cross-entity "type and see suggestions" search for a toolbar
search box (Claude Design: Crown Solar Admin Dashboard — Dashboard v2 ·
Plants toolbar search suggestions), returning at most limit hits re-filtered
by the caller's own authorization per entity type.
- HTTP method:
GET - Endpoint:
/v1/search/suggestions - Authentication: Required (same four Cognito clients as every other
route — see
GET /v1/lookupabove). - Authorization: Per-hit, via each registered type's own
authorize/authorizeMany(registerLookupType,packages/core/src/codes.ts) — a hit the caller cannot view is dropped silently, never surfaced and then rejected. 004 and 005 register real lookup types for their prefixes; 006 registersWO-(work orders). Thedevice,serial,OP,BLKandFWtypes were removed by ADR 0012 phase 2. Platform mode (ADR 0015) has its own rule, described in Platform-wide search. - Side effects: none. Pure read.
- DynamoDB calls: one
Queryper searched entity type (parallel fan-out) against that type'sSRCH#<org>#<collection>#<first-2-chars>token partition (data-model.md§2.7),Limit: 3 × limitper type for word-filtering/authorization margin — never aScan. Tokens are written by the stream router fromregistry/collections.tsregistrations (packages/core/src/stream/plan.ts), so a hit only exists once the entity's stream record has been processed — eventually consistent, not read-your-writes (see Edge cases). - Throttle: this route carries its own per-route throttle,
{ rate: 20, burst: 40 }(lib/routes.ts), tighter than the API's default — it's the one discovery route that fans out aQueryper requested/registered type per keystroke.
Request
Headers
| Header | Required | Value |
|---|---|---|
Authorization | Yes | Bearer <token> |
X-Org-Id | Yes | The caller's active organisation, as a ULID. There is no active-org concept yet in 002 (feature 003's job) — this header is currently the only source of org context, so it's required on every call, not optional like on GET /v1/lookup. |
Path parameters: none.
Query parameters
| Param | Type | Required | Validation |
|---|---|---|---|
q | string | Yes | Trimmed and normalised (NFKD diacritic-folded, lower-cased, non-alphanumerics collapsed to spaces) before matching; 2-64 chars after trimming |
types | string[] | No | Either repeated (types=plant&types=tag) or comma-joined (types=plant,tag) — both accepted and merged. Each value must be a type registered via registerLookupType; omitted → every registered type is searched, in registration order |
limit | integer | No | 1-20, default 6. Not the usual list-endpoint cap of 50 — this is a typeahead, not a paged list |
operatorOrgId | ULID | No | Platform mode only: search just this org instead of every org. Sent by any other caller, or malformed → 400 VALIDATION_FAILED (details.field: "operatorOrgId") |
This is a strict route: q, types and limit are the only accepted
query parameters — any other one is rejected.
Matching semantics: the first word of q is matched as a prefix against
the token partition; any additional words are matched as a substring
against the token's own denormalised text (words: every searchable field of
the entity, normalised). "ghori kar" matches an entity tokenised from
"Ghori Residence, Karachi" but not one with only "Ghori Towers, Lahore".
Punctuation splits words, so a code query PL-0003 is the two words pl and
0003.
Fixed 2026-11-03, committed, not yet deployed. Before this, token rows stored no
entityIdand nowords, and theirlabelwas the field name. In practice A12 returned no hit for any stream-written token, and could not have matched a second word or shown the entity's name. After the deploy, rows written by the stream-router are correct straight away; older rows neednpm run rebuild:projectionsper org and collection (see Operations). Until that runs, an old row matches a one-word query but shows the field name (name) as itslabel.
Request body: none.
Response
Structure (SuggestionItem[], wrapped — see
Types & schemas):
{
items: Array<{
type: string; // registered search/lookup entity type, e.g. "plant"
id: string; // ULID of the matched entity — for type `customer` it is the CUSTOMER ORG's id (`customerOrgId`), not a user or membership id
label: string; // the entity's display value: plant name, customer/partner name, tag label
sublabel?: string; // the entity's display code (`PL-`, `CU-`, `PB-`, `TG-`), when it has one
matchedField: string; // which field matched, e.g. "name", "serial"
code?: string; // the entity's display code, when it has one
orgId?: string; // the org that owns the hit; always set since ADR 0015. Open the result in this org
orgName?: string; // platform mode only: the owning org's name
orgKind?: 'OPERATOR' | 'PARTNER' | 'CUSTOMER' | 'PERSONAL'; // platform mode only; PERSONAL = an Independent End User's own org
}>;
}
A customer hit that matched only on the contact name or email is dropped for a caller below customers: MANAGE in
the org (the Installer template holds VIEW; RBAC-S7, 2026-11-24), so a search cannot confirm a customer's address.
Platform-wide search (Super Admin and Administrator)
Committed 2026-11-03 (ADR 0015, docs/adr/0015-platform-wide-search.md in the cse-http-be repo),
not yet deployed.
- Who: a caller whose
X-Org-Idis a PLATFORM org (Crown HQ) in which they hold the built-in Super Admin or Administrator role, ACTIVE, scopeALL(MFA policy applied as on any request). A custom role in the PLATFORM org,plants ≥ VIEWin any org, and every other role stay org-scoped: they search only theX-Org-Idorg, with per-hit authorization as above.operatorOrgIdcan never switch platform mode on. - What: without
operatorOrgId, every org: Businesses, partners, customers and Independent End Users' personal orgs. Plants created on mobile and on the web are included once they are indexed. WithoperatorOrgId, that one org only. - Which hits: those whose owning org is
ACTIVEand not PLATFORM. Hits of suspended or closed orgs are dropped silently. - Response: every item carries
orgId,orgNameandorgKind. Show the owner (e.g. "Crown R&D Lab · Ghori Solar Pvt Ltd") and open the result in that org (X-Org-Id: <orgId>), which a platform Super Admin/Administrator may select. - How: one
Queryper type on the all-org view of the token rows (GSI1,SRCH#ALL#<collection>#<p2>), plus oneBatchGetItemfor the owning orgs. Token rows written before this change are not on that view untilnpm run rebuild:projections -- --all-orgs --executehas run (see Operations). - Audit: platform reads in other orgs are not written to those orgs' access logs (existing policy: only state-changing platform actions are).
Platform-mode response — illustrative example
Derived from SuggestionItem in packages/core/src/schemas.ts; not a captured call.
{
"items": [
{ "type": "plant", "id": "01J9Z4A1B2C3D4E5F6G7H8J9K0", "label": "Crown R&D Lab", "sublabel": "PL-0003", "code": "PL-0003",
"matchedField": "name", "orgId": "01J9Z3K8N4R6X2QYV7M1WB0T3F", "orgName": "Ghori Solar Pvt Ltd", "orgKind": "OPERATOR" }
]
}
Customer hits: a customer item's id is the customer organisation's id — the customerOrgId of the CUSTOMER_PROFILE record the search token was projected from (packages/core/src/customers/projections.ts). Use it as the {customerOrgId}/org id when opening the customer.
Results are grouped by entity type in request order (or registration order
when types was omitted), token order within a type, then truncated to
limit across all types combined — not limit per type.
Successful response — illustrative example
{
"items": [
{ "type": "plant", "id": "01J9Z4A1B2C3D4E5F6G7H8J9K0", "label": "Ghori Residence", "matchedField": "name" }
]
}
An empty, still-successful response (no hits, or every hit denied by authorization):
{ "items": [] }
Failure response — validation failure (illustrative)
An unregistered types value — note details.allowed lists the real options,
unlike GET /v1/lookup's non-disclosure 404:
{ "error": { "code": "VALIDATION_FAILED", "message": "Unknown search type \"bogus\"", "details": { "allowed": ["plant"] }, "requestId": "Abc123Xyz=" } }
q too short/long, bad limit, or any other schema violation:
{ "error": { "code": "VALIDATION_FAILED", "message": "Invalid search query", "details": { "formErrors": [], "fieldErrors": { "q": ["String must contain at least 2 character(s)"] } }, "requestId": "Abc123Xyz=" } }
A missing X-Org-Id:
{ "error": { "code": "VALIDATION_FAILED", "message": "X-Org-Id header is required", "requestId": "Abc123Xyz=" } }
An unknown query parameter:
{ "error": { "code": "VALIDATION_FAILED", "message": "Unknown query parameter", "details": { "unknown": ["foo"] }, "requestId": "Abc123Xyz=" } }
HTTP status codes
| Status | code | When | FE guidance |
|---|---|---|---|
| 200 | — | Always, even with zero hits — an empty items is not an error | Render an empty state, not an error, for items: [] |
| 401 | — (gateway body {"message":"Unauthorized"}) | Missing/invalid/expired token, or a client not accepted by the authorizer | Re-authenticate / refresh the token |
| 401 | SESSION_REVOKED | The token is valid but its session was revoked (standard { error: { code, message } } envelope, from the Lambda, not the gateway) | Sign the user in again |
| 400 | VALIDATION_FAILED | An unknown query parameter, q/limit failing the schema, an unregistered types value (details.allowed), a missing X-Org-Id, or operatorOrgId malformed or sent outside platform mode (details.field) | Fix the client request before retrying — all of these are client bugs, not transient |
| 403 | FORBIDDEN / ACCOUNT_SUSPENDED | X-Org-Id names an organisation the caller is not a member of (or the membership is suspended) — checked before any lookup/search runs (004, T004-1212) | Don't retry; switch to an org the user belongs to |
| 429 | — (gateway body {"message":"Too Many Requests"}) | The route's own API Gateway throttle ({ rate: 20, burst: 40 }, tighter than the API default) is exceeded — rejected before the Lambda runs, so no X-Request-Id | Back off (debounce keystrokes client-side rather than firing a request per character) and retry |
| 500 | INTERNAL | Unexpected server error | Retry once; if it persists, report it |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB throttled/unavailable | Retry with backoff; honor Retry-After if present |
Edge cases
- Silent drop, not an error, for denied hits. A hit the caller's
authorize/authorizeManydenies is simply absent fromitems— the response is still200, and the FE has no way to tell "zero matches" apart from "matches existed but were all denied". Same non-disclosure reasoning asGET /v1/lookup's 404. - Eventual consistency. Search tokens are written by the stream router reacting to a DynamoDB stream record, not inside the original write's own transaction — an entity created or renamed a moment ago may not be searchable yet. Don't build a "search immediately after create" flow that assumes read-your-writes here.
limittruncates across types, not per type. Requestingtypes=plant,tag&limit=6can return 6 plants and 0 tags (or any other split) — it is not an even distribution.- Searchable types (004).
plant,customer,partnerandtagare registered; their search collections are the stream entity typesPLANT,CUSTOMER_PROFILE,PARTNER_PROFILEandTAG(SEARCH_COLLECTION_ENTITY_TYPESinpackages/core/src/plants/lookup.ts). Tags are tokenised on theirlabelsince 2026-11-03 (committed, not yet deployed); before that no tag ever matched. Omittingtypessearches all four; atypesvalue outside that set is400 VALIDATION_FAILEDwithdetails.allowedlisting the registered ones. Hits the caller may not view are dropped silently (see above). - Membership is checked. An
X-Org-Idnaming an org the caller is not a member of returns403 FORBIDDENbefore any search runs; it never returns hits from that org. X-Org-Idis mandatory here, unlike onGET /v1/lookup. 002 has no active-org concept (feature 003's job) — this route cannot scope a search to an organisation any other way yet, so a missing header is always a400, never silently treated as "search nothing" or "search everything".
GET /v1/catalog/{name} — Registered vocabulary lookup
Purpose: serves a registered vocabulary (plant types, solar modes, grid
connections, countries, timezones) for populating a dropdown, so the FE
never hand-maintains a copy of a schemas.ts enum client-side.
- HTTP method:
GET - Endpoint:
/v1/catalog/{name} - Authentication: Required (same four Cognito clients as every other route).
- Authorization: None beyond being signed in — any authenticated caller may read any registered catalog. There is no per-resource or per-org access control on this route.
- Side effects: none. Pure read, no DynamoDB involved at all — catalogs
are built from code (
registry/catalogs.ts) at Lambda cold start. - Caching:
ETagis a content hash of the catalog's items (packages/core/src/registry/catalogs.ts, first 12 hex chars of a SHA-256), stable until that vocabulary's values change;Cache-Control: private, max-age=300lets a client cache for 5 minutes without re-fetching every screen load.
Request
Headers
| Header | Required | Value |
|---|---|---|
Authorization | Yes | Bearer <token> |
If-None-Match | No | A previously received ETag value (quoted), e.g. "abc123def456" — a match short-circuits to 304 with no body |
Path parameters
| Param | Type | Required | Validation |
|---|---|---|---|
name | string | Yes | One of the registered catalog names below. Any other value is 404 NOT_FOUND |
002's registered catalog names: plant-types, solar-modes,
grid-connections, countries, timezones. Later features register their
own (planned: levels, categories, work types, priorities, tariff types,
device types). The former device-models and commands catalogues (and
their dedicated routes) were removed by ADR 0012: both names now reach this
{name} route and return 404 NOT_FOUND like any unregistered name; the
device-model and command catalogues are served by the TCP server.
This route accepts no query parameters at all — sending any is rejected.
Request body: none.
Response
Structure (CatalogResponse — see
Types & schemas):
{
name: string;
version: string; // content-hash version, also carried in the ETag header (quoted)
items: Array<{ value: string; label: string; deprecated?: boolean }>;
}
Successful response — illustrative example
{
"name": "plant-types",
"version": "abc123def456",
"items": [
{ "value": "RESIDENTIAL", "label": "Residential" },
{ "value": "COMMERCIAL", "label": "Commercial" },
{ "value": "INDUSTRIAL", "label": "Industrial" }
]
}
Response headers on 200: ETag: "abc123def456", Cache-Control: private, max-age=300.
Failure response — not found (illustrative)
{ "error": { "code": "NOT_FOUND", "message": "Catalog not found", "requestId": "Abc123Xyz=" } }
Failure response — validation failure (illustrative)
Any query parameter at all (this route takes none):
{ "error": { "code": "VALIDATION_FAILED", "message": "This route accepts no query parameters", "requestId": "Abc123Xyz=" } }
HTTP status codes
| Status | code | When | FE guidance |
|---|---|---|---|
| 200 | — | name is a registered catalog, and If-None-Match (if sent) didn't match the current ETag | Cache for up to 5 minutes per Cache-Control; populate the dropdown from items |
| 304 | — (no body) | If-None-Match matched the catalog's current ETag | Keep using the previously cached items |
| 401 | — (gateway body {"message":"Unauthorized"}) | Missing/invalid/expired token, or a client not accepted by the authorizer | Re-authenticate / refresh the token |
| 401 | SESSION_REVOKED | The token is valid but its session was revoked (standard { error: { code, message } } envelope, from the Lambda, not the gateway) | Sign the user in again |
| 404 | NOT_FOUND | name is not a registered catalog (including device-models/commands) | Treat as a client bug — the set of valid names is fixed and known at build time, not user input |
| 400 | VALIDATION_FAILED | Any query parameter was sent | Fix the client request — this is a client bug, not retryable as-is |
| 500 | INTERNAL | Unexpected server error | Retry once; if it persists, report it |
| 503 | DEPENDENCY_UNAVAILABLE | N/A today (no DynamoDB call on this route) — listed for completeness with every other route's error table | — |
Edge cases
version/ETagonly changes when the vocabulary's values change, not on every deploy or cold start — it's a content hash of the items, so the same five 002 catalogs produce the sameETagacross restarts.deprecated: trueon an item is a value change too (it changes the hash), so a value transitioning to deprecated invalidates caches.Intl.DisplayNames/Intl.supportedValuesOfoutput (countries,timezones) is itself ICU-version-dependent — a Node/ICU upgrade can change a label or the exact timezone list, and therefore the hash, with no code change in this repo. See alsoCatalogResponse.device-models/commandsare gone (ADR 0012). They return the same404 NOT_FOUNDas a typo inname— fetch those catalogues from the TCP server instead.- No per-caller variation. Every signed-in caller gets the identical
catalog for a given
name— there is no per-org or per-role filtering, soCache-Control: privateis about per-client HTTP caching hygiene, not about the data actually varying per caller.